python / intermediate
Snippet
Django Context Processors for Global Template Variables
Context processors are functions that run before every template render, adding variables to the template context globally. This is ideal for data needed across multiple pages like navigation categories, user notifications, or shopping cart contents.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
# myapp/context_processors.pyfrom .models import Categorydef categories_processor(request):return {'all_categories': Category.objects.all()}# In settings.py add to TEMPLATES configuration:# 'context_processors': [# 'myapp.context_processors.categories_processor',# ]
django
Breakdown
1
def categories_processor(request):
Function receives the current request object and must return a dictionary of template variables
2
'all_categories': Category.objects.all()
Query all categories from database to make available in every template
3
TEMPLATES configuration
Register the context processor in Django settings to activate it project-wide