django 页面查询数据库

1. views.py  查库:
from django.shortcuts import render
from . import models
from django.http import HttpResponse

def index(request):
return HttpResponse("welcome to django!")

def html_index(request):
categories = models.Category.objects.all()
# locals 是取函数内的一个局部变量 放到一个字典里
return render(request,'index.html',locals())

2. index.xml 页面中,在需要展示数据的位置
<ul class="list-group list-group-flush f-16">


{% for category in categories %}
<li class="list-group-item d-flex justify-content-between align-items-center pr-2 py-2">
<a class="category-item" href="/category?id={{ category.id }}"
title="查看【{{ category.name }}】分类下所有文章"> {{ category.name }} </a>
<span class="badge text-center" title="当前分类下有6篇文章">{{ category.article_set.count }}</span>
</li>

{% endfor %}


</ul>
3. 刷新页面,就可以显示数据库内容了
posted @ 2021-05-24 15:03  Mia妈妈加油呀  阅读(520)  评论(0)    收藏  举报