为所有视图提供额外的上下文 [英] Provide extra context to all views

查看:77
本文介绍了为所有视图提供额外的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django为我的团队建立一个项目管理网站。我的基本模板包括一个侧边栏菜单,其中包含所有项目和用户的列表,分别链接到该用户或项目的 DetailView

I'm putting together a project management website for my team using django. My base template includes a sidebar menu which contains a list of all projects and users, linking to a DetailView for that user or project, respectively.

我的问题是我需要为每个视图提供 User Project 模型,因此我可以渲染侧边栏。我知道如何添加额外的上下文;问题是我感觉自己在每个级别上修改上下文都违反了DRY。是否可以简单地重新定义基础 TemplateClass ,以便所有子类- ListView DetailView 等-是否包含修改后的上下文?

My problem is that I need to provide the User and Project models to every view so that I can render that sidebar. I know how to add extra context; the problem is that I feel like I'm violating DRY by modifying the context at each level. Is it possible to simply redefine the base TemplateClass so that all child classes—ListView, DetailView, etc.—contain the modified context?

在相关说明中,如果这是设置项目的糟糕方法,请允许我

On a related note, if this is a terrible way to set up the project, let me know that as well.

推荐答案

您可以使用模板上下文处理器

myapp / context_processors.py

from django.contrib.auth.models import User
from myapp.models import Project

def users_and_projects(request):
    return {'all_users': User.objects.all(),
            'all_projects': Project.objects.all()}

然后将此处理器添加到 TEMPLATE_CONTEXT_PROCESSORS 设置:

And then add this processor to the TEMPLATE_CONTEXT_PROCESSORS setting:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'myapp.context_processors.users_and_projects',
)

上下文处理器将针对您的所有请求运行。如果您只想对使用 base.html 呈现的视图运行这些查询,则另一种可能的解决方案是自定义任务标签

Context processor will run for ALL your requests. If your want to run these queries only for views which use the base.html rendering then the other possible solution is the custom assignment tag:

@register.assignment_tag
def get_all_users():
    return User.objects.all()

@register.assignment_tag
def get_all_projects():
    return Project.objects.all()

c $ c> base.html 模板:

And the in your base.html template:

{% load mytags %}

{% get_all_users as all_users %}
<ul>
{% for u in all_users %}
    <li><a href="{{ u.get_absolute_url }}">{{ u }}</a></li>
{% endfor %}
</ul>

{% get_all_projects as all_projects %}
<ul>
{% for p in all_projects %}
    <li><a href="{{ p.get_absolute_url }}">{{ p }}</a></li>
{% endfor %}
</ul>

这篇关于为所有视图提供额外的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆