Django通过ListView类将参数传递给网页

时间:2016-03-08 10:14:28

标签: django python-3.x

我有urls.py

urlpatterns = [
url(r'^index',
    ListView.as_view(queryset=Post.objects.all().order_by("-date")[:4], template_name="personal/index.html")),
]

和模板文件header.html,我有下一行

< header class="intro-header" style="background-image: url('{% static background_image %}')">
. . .
</header>

如您所见,我正在尝试将背景图像设置为标题,哪个路径保存在background_image变量中,我想知道如何传递此参数

有没有办法,或者我完全错了?

1 个答案:

答案 0 :(得分:2)

您可以通过继承视图并覆盖get_context_data来向Django CBV的上下文添加额外的变量:

class PostListView(ListView):
    queryset = Post.objects.all().order_by("-date")[:4]
    template_name = "personal/index.html"

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        context['background_image'] = 'personal/img/home-bg.jpg'
        return context

然后更新您的网址格式以使用您的新视图:

url(r'^index', PostListView.as_view())