如何在Django基本模板中呈现查询集? [英] How I do render a queryset in a Django base template?
问题描述
我有一个基本模板,该模板可以扩展到项目中几乎所有其他模板.我正在尝试使用数据库中的一些查询集填充类别导航栏,但是我的方法失败了.由于基本模板没有url,因此我发现很难渲染.这是我尝试过的:
I have a base template which extends to almost every other templates in my project. I am trying to populate my categories navigation bar with some queryset from my database but am failing with my approach. Since the base template has no url, I am finding it difficult to render. This is what I've tried:
这是我的视图功能
def base(request):
categories = list(Category.objects.all())
context = {
'categories': categories
}
return render(request, 'ads/base.html', context)
这是我的html
{% for category in categories %}
<div class="nav-item dropdown">
<a href="#" class="nav-link dropdown-toggle" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{ category.name }}
<span class="float-right text-muted">
<small>
<i class="fas fa-chevron-down"></i>
</small>
</span>
</a>
</div>
{% endfor %}
我只想用类别queryset填充导航栏
I just want to populate my navbar with the categories queryset
推荐答案
即使 base
视图具有URL,也不会有任何区别.URL触发一个视图,该视图呈现响应.模板与它没有(太多)关系.有时将模板用作生成此类响应的方法.但是它只能使用以某种方式传递的数据进行渲染.例如,通过该视图或模板标签,上下文处理器等.
Even if the base
view had a URL, that would not make any difference. A URL triggers a view, and that view renders a response. A template has not (much) to do with it. A template is sometimes used as a way to generate such response. But it can only render with data that is passed somehow. For example through that view, or through template tags, context processors, etc.
例如,我们可以定义一个上下文处理器.在您的应用中,您可以在 context_processors.py
文件中定义一个函数:
We can for example define a context processor. In your app, you can define a function in the context_processors.py
file:
# app/context_processors.py
def categories(request):
from app.models import Category
return {'categories': Category.objects.all()}
然后,您可以在 settings.py
中将该函数添加到上下文处理器中:
In the settings.py
you can then add the function to the context processors:
# settings.py
# ...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'app.context_processors.categories'
],
},
},
]
现在,每次渲染模板时,都将向映射到 Category.objects.all()
查询集的上下文中添加 categories
变量. QuerySet
的计算是惰性的,因此,如果您不需要对其进行迭代,则不会在数据库上执行查询.
Now each time you render a template, you will add a categories
variable to the context that is mapped on the Category.objects.all()
queryset. QuerySet
s are evaluated lazily, so in case you do not need to iterate over it, the query is not performed on the database.
这篇关于如何在Django基本模板中呈现查询集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!