Django:ListView。我在哪里可以声明我想要在模板上拥有的变量?

时间:2016-05-22 04:24:36

标签: python django listview templates

我的应用程序中的一个表名为Gallery,我有以下类列出该表中的所有对象:

from django.views.generic import ListView
from galleries.models import Gallery 

class GalleryList(ListView):
 template_name = "path/to/template"
 context_object_name = "object_list"

 def queryset(self):
  return Gallery.objects.order_by('-title')[:20]

它完成了这项工作。在我的模板上,我执行以下操作:

{% block gallery_list %}
    <h1>Gallery List</h1>
    <ul>
        {% for gallery in object_list %}
            <li><img src="{{ gallery.thumbnail.url }}" />{{ gallery.title }}</li>
        {% endfor %}
    </ul>
{% endblock %}

一切都按预期工作。这里的问题是,在我的base.html模板上,{% block title %}代码为meta title,标题中为{% block description %}代码meta description。我希望能够在某处声明它并将其传递给视图。需要明确的是,变量titledescription是字符串(例如:title="List of all galleries on website")。

在视图中我想做类似的事情:

{% extends "base.html" %}

{% block title %}{{ title }}{% endblock %}
{% block description %}{{ description|default:title }}{% endblock %}

但是,在课程GalleryList上,我不知道在哪里声明变量titledescription。我不知道Django是否可行或适当。我想做对的。

另外,因为我有一个服装模板可以列出我可以做的所有画廊:

{% extends "base.html" %}

{% block title %}List of all galleries on website{% endblock %}
{% block description %}List of all galleries on website...{% endblock %}

但话说回来,我不知道这对于编码良好的Django应用程序是否合适。我是Django的初学者,我想知道如何解决这个问题。希望我的问题很清楚。

1 个答案:

答案 0 :(得分:3)

您可以覆盖ListView s get_context_data method以向上下文添加任何其他上下文变量:

class GalleryList(ListView):

    def get_context_data(self, **kwargs):
        ctx = super(GalleryList, self).get_context_data(**kwargs)
        ctx['title'] = 'My Title'
        ctx['description'] = 'My Description'
        return ctx

另一种方法 - 拥有填写此信息的模板 - 也是合理的。哪个更好取决于数据的动态程度。如果标题/描述基于模型数据或某些其他因素,那么在视图中设置它是有意义的。如果针对特定模板进行了修复,那么放入base.html扩展的模板可能会更加清晰。

相关问题