Consider displaying a list of article categories or shopping cart counts in your site header. Passing categories = Category.objects.all() manually in every view function violates DRY. Django solves this with Context Processors.
Create a file named context_processors.py inside your core app:
# blog/context_processors.py
from django.core.cache import cache
from .models import Category
def site_wide_categories(request):
"""Injects cached navigation categories into every template context."""
categories = cache.get('nav_categories')
if categories is None:
categories = list(Category.objects.all())
cache.set('nav_categories', categories, 60 * 60) # Cache for 1 hour
return {
'all_categories': categories,
'site_name': 'Veewom Programming',
'support_email': 'support@veewom.com'
}
def cart_counter(request):
"""Calculates total shopping cart quantity from session."""
cart = request.session.get('cart', {})
total_items = sum(cart.values()) if isinstance(cart, dict) else 0
return {
'cart_total_count': total_items,
'is_dark_mode': request.session.get('theme_mode', 'light') == 'dark'
}
Add your processor path under TEMPLATES['OPTIONS']['context_processors']:
# mywebsite/settings.py
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',
# Custom Project Context Processors
'blog.context_processors.site_wide_categories',
'blog.context_processors.cart_counter',
],
},
},
]
Now, {{ all_categories }}, {{ site_name }}, {{ cart_total_count }}, and {{ support_email }} are available instantly inside any HTML template without modifying a single view!
| Feature | Context Processor | Inclusion Template Tag |
|---|---|---|
| Scope | Global — runs on every rendered template. | Local — runs only where explicitly loaded. |
| Performance Impact | Must be lightweight or cached; runs on all requests. | Zero impact on pages where tag is not loaded. |
| Typical Use Cases | Logged-in user roles, site title, cart item count. | Sidebar widgets, comment threads, dynamic carousels. |
Always benchmark your context processors. If an un-cached query takes 25ms inside a context processor, every single page on your entire website is penalized by 25ms before any view code even begins executing.
Broaden your backend architecture, REST API design, and production engineering expertise:
Access injected global variables seamlessly in any child template.
Register custom processors in TEMPLATES['OPTIONS']['context_processors'].
Cache heavy context processor calculations to protect page load speed.
Interview questions exploring default Django context processors.