如何解决基于函数和基于类的视图的 Django“上下文”
帮助我了解如何使用 Django 的 context
--是否与在基于函数和基于类的视图中使用 context
相关的问题:
我创建了两个视图(index
和 post_list
)和各自的模板(在 Mozilla Django Tutorial 的评估部分之后)。 index
的代码有效,但 post_list
的相同代码无效。这是为什么?
查看 #1
def index(request):
post_list = Post.objects.all()
num_posts = Post.objects.all().count()
num_comments = Comment.objects.all().count()
num_authors = Author.objects.count()
num_commenters = Commenter.objects.count()
context = {
'num_posts': num_posts,'num_comments': num_comments,'num_authors': num_authors,'num_commenters': num_commenters,'post_list' : post_list,}
return render(request,'index.html',context=context)
模板 #1 -- 作品:
{% block content %}
<h1>Index:</h1>
This blog has a total of {{num_posts}} posts by {{ num_authors}} authors.
{% endblock %}
视图#2
class PostListView(generic.ListView):
model = Post
post_list = Post.objects.all()
num_posts = Post.objects.all().count()
num_authors = Author.objects.count()
template_name = 'blog/post_list.html'
context = {
'num_posts': num_posts,#'num_authors': num_authors,# Removed b/c it doesn't work
'post_list' : post_list,}
def get_context_data(self,**kwargs):
context = super(PostListView,self).get_context_data(**kwargs)
context['num_authors'] = Author.objects.count() # But this works!
return context #edited,this line was left out in the original post
模板#2 - 不完全有效:
{% block content %}
<h1>All Posts:</h1>
This blog has a total of {{num_posts}} posts by {{ num_authors}} authors.
{% endblock %}
解决方法
您对 get_context_data
方法的定义不会更新您希望在模板中使用的所有变量。例如,context
类变量与您在 context
方法中返回的 get_context_data
变量不同。因此,您在模板中有权访问的唯一变量是 num_authors
。为了确保您的模板中有所有需要的变量,您需要编辑 get_context_data
以使用在类级别定义的字典更新 context
:
class PostListView(generic.ListView):
model = Post
post_list = Post.objects.all()
num_posts = Post.objects.all().count()
num_authors = Author.objects.count()
template_name = 'blog/post_list.html'
context_vars = {
'num_posts': num_posts,'num_authors': num_authors,'post_list' : post_list,}
def get_context_data(self,**kwargs):
context = super(PostListView,self).get_context_data(**kwargs)
context.update(PostListView.context_vars)
return context
对您的原始代码片段进行了两个主要更新:类变量 context
更改为 context_vars
以避免冲突和混淆; context
方法中的 get_context_data
变量是 updated
,其内容为 context_vars
。这将确保在类级别(即 PostListView.context_vars
)定义的所有内容都包含在您的模板中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。