上下文数据

有时,你的模板需要更多信息。例如,我们希望将用户放在页面的标题中,并在注销链接旁边添加指向其配置文件的链接。在这些情况下,请使用 get_context_data 方法。

views.py

class BookView(DetailView):
    template_name = "book.html"

    def get_context_data(self, **kwargs)
        """ get_context_data let you fill the template context """
        context = super(BookView, self).get_context_data(**kwargs)
        # Get Related publishers
        context['publishers'] = self.object.publishers.filter(is_active=True)
        return context

你需要在超类上调用 get_context_data 方法,它将返回默认的上下文实例。你添加到此词典的任何项目都可供模板使用。

book.html

<h3>Active publishers</h3>
<ul>
  {% for publisher in publishers %}
    <li>{{ publisher.name }}</li>
  {% endfor %}
</ul>