Provide extra context to all views

前端 未结 1 1129
忘掉有多难
忘掉有多难 2020-12-03 05:44

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, linkin

相关标签:
1条回答
  • 2020-12-03 05:53

    You could use the template context processor:

    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()}
    

    And then add this processor to the TEMPLATE_CONTEXT_PROCESSORS setting:

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

    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()
    

    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>
    
    0 讨论(0)
提交回复
热议问题