如何在Django中使用TemplateView中的get_context_data

时间:2022-08-17 19:22:36

I'm trying to do something like this:

我试着做这样的事情:

class AboutView(TemplateView):
    template_name = 'about.html'

    def get_context_data(self, **kwargs):
        context = super(AboutView, self).get_context_data(**kwargs)
        context['dahl_books'] = Books.objects.filter(author="Dahl')

When I try to access dahl_books in my template like this:

当我试图访问我模板中的dahl_books时,如下所示:

{% for book in dahl_books %}

dahl_books is not available in the template context, even though the Books QuerySet returned a non-zero number of books. ....am I doing something wrong in either my template or in get_context_data?

dahl_books模板中是不可用的背景下,即使书QuerySet返回一个非零数的书籍。....我在模板或get_context_data中做错了什么吗?

1 个解决方案

#1


48  

I can't test it, but I bet you need

我不能测试它,但我打赌你需要

return context

at the end of get_context_data :)

在get_context_data的末尾:)

#1


48  

I can't test it, but I bet you need

我不能测试它,但我打赌你需要

return context

at the end of get_context_data :)

在get_context_data的末尾:)