Django - How to make a variable available to all templates?

二次信任 提交于 2019-11-26 19:54:58
Victor Castillo Torres

What you want is a context processor, and it's very easy to create one. Assuming you have an app named custom_app, follow the next steps:

  • Add custom_app to INSTALLED_APPS in settings.py (you've done it already, right?);
  • Create a context_processors.py into custom_app folder;
  • Add the following code to that new file:

    def categories_processor(request):
     categories = Category.objects.all()            
     return {'categories': categories}
    
  • Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py

    TEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", )
    

And now you can use {{categories}} in all the templates :D

As of Django 1.8

To add a TEMPLATE_CONTEXT_PROCESSORS, in the settings you must add the next code:

TEMPLATES[0]['OPTIONS']['context_processors'].append("custom_app.context_processors.categories_processor")

Or include that string directly in the OPTIONS.context_processors key in your TEMPLATES setting.

As seen in this example, post Django 1.3 you can simply use render instead of render_to_response which doesn't require you to explicitly pass the context processor.

def another_view_method(request):
    categories = Category.objects.all()
    return render(
        'eg/front_page.html',
        {'is_logged_in': is_logged_in(request), 'categories':categories}
    )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!