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

the*_*101 4 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")),
]
Run Code Online (Sandbox Code Playgroud)

和一个模板文件 header.html 在那里我有下一行

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

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

有什么办法可以做到,还是我做错了?

Ala*_*air 6

您可以通过子类化视图和覆盖来向 Django CBV 的上下文添加额外的变量get_context_data

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
Run Code Online (Sandbox Code Playgroud)

然后更新您的 url 模式以使用您的新视图:

url(r'^index', PostListView.as_view())
Run Code Online (Sandbox Code Playgroud)