In Django, a context processor is a Python function that takes a request object as an argument and returns a dictionary of data that gets added to the context of every template rendered using Django's RequestContext.
Purpose
Context processors let you inject common variables into the context of all templates, without having to explicitly pass them in each view.
Example Use Case
Imagine you want your site to always display the logged-in user's name and the current year in the footer. Instead of passing that manually from every view, you can use a context processor.
How It Works
- Define a context processor function:
# myapp/context_processors.py
from datetime import datetime
def global_variables(request):
return {
'current_year': datetime.now().year,
'user_ip': request.META.get('REMOTE_ADDR'),
}
- Add it to settings:
In settings.py, add it to TEMPLATES:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
...
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'myapp.context_processors.global_variables', # <-- custom processor
],
},
},
]
Use in template:
<footer>
© {{ current_year }} | Your IP: {{ user_ip }}
</footer>
Built-in Context Processors
Some useful built-in ones:
django.template.context_processors.request --> adds the request object.
django.contrib.auth.context_processors.auth --> adds user, perms.
django.template.context_processors.static --> adds STATIC_URL.
Summary
A context processor is a handy way to share variables across all templates without manually including them in every view, helping to keep your code DRY and centralized.
Top comments (0)