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_apptoINSTALLED_APPSinsettings.py(you’ve done it already, right?); - Create a
context_processors.pyintocustom_appfolder; -
Add the following code to that new file:
def categories_processor(request): categories = Category.objects.all() return {'categories': categories} -
Add
context_processors.pytoTEMPLATE_CONTEXT_PROCESSORSinsettings.pyTEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", )
And now you can use {{categories}} in all the templates 😀
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.