The Context
The context is the dictionary of data passed from view to template.
The context is how a view hands data to a template. It is a plain Python dictionary: keys become variable names in the template, values become their contents.
Django also injects a few variables automatically through context processors — for example request, user and messages are available in every template.
Example
def profile(request):
context = {
"user_name": "Ada",
"posts": ["First", "Second"],
"is_premium": True,
}
return render(request, "profile.html", context)
# In profile.html:
# {{ user_name }}, {{ posts|length }} posts
# {% if is_premium %}Premium member{% endif %}When to use it
- A developer passes the current user's name and unread message count to a dashboard template via context.
- A team writes a context processor to inject the current site's branding data into every template automatically.
- A developer passes a paginator object in context so the template can render page navigation controls.
More examples
Pass data through context dict
Builds a context dictionary with multiple values and passes it all to the template at once.
def dashboard(request):
context = {
"user": request.user,
"unread_count": request.user.messages.filter(read=False).count(),
"recent_posts": Post.objects.order_by("-created")[:5],
}
return render(request, "dashboard.html", context)Custom context processor
A custom context processor injects branding values into every template without repeating them in each view.
# myapp/context_processors.py
def site_branding(request):
return {
"site_name": "SoundsCode",
"support_email": "[email protected]",
}
# settings.py OPTIONS -> context_processors -> add:
# 'myapp.context_processors.site_branding'Access nested context values
Accesses nested object attributes and uses the pluralize filter on a context integer.
<!-- template -->
<p>Hello, {{ user.first_name }}!</p>
<p>You have {{ unread_count }} unread message{{ unread_count|pluralize }}.</p>
{% for post in recent_posts %}
<li>{{ post.title }}</li>
{% endfor %}
Discussion