Context processors
Django · Reference cheat sheet
Context processors
Django · Reference cheat sheet
📋 Overview
Context processors add variables to every template context for a given engine. Register callables under TEMPLATES[i]["OPTIONS"]["context_processors"]. Built-ins expose request, user, perms, messages, and debug info. Keep processors cheap—they run on every render.
🔧 Core concepts
| Built-in | Provides |
|---|---|
debug | debug, sql_queries (DEBUG) |
request | request |
auth | user, perms |
messages | messages |
media / static | MEDIA_URL, STATIC_URL |
Signature: def processor(request) -> dict. Only applied when using RequestContext / render() (not bare Context + Template.render without request).
💡 Examples
Custom processor:
# myapp/context_processors.py
from django.conf import settings
def site_meta(request):
return {
"SITE_NAME": getattr(settings, "SITE_NAME", "My Site"),
"SUPPORT_EMAIL": "support@example.com",
}Settings:
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"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.site_meta",
],
},
},
]Template usage:
<title>{{ SITE_NAME }}</title>
{% if user.is_authenticated %}
Hi {{ user.username }}
{% endif %}⚠️ Pitfalls
- DB queries in processors → N× cost on every page.
- Assuming
requestexists when rendering withoutRequestContext. - Name collisions with view context keys (view wins or merges—avoid overlap).
- Putting secrets into global template context.
- Forgetting to add the processor path after creating it.