python / expert
Snippet
Django Context Processors for Dynamic Template Global Data
Context processors are callables that receive the request object and return a dictionary of variables to merge into every template context. This example demonstrates a production-ready context processor that provides site-wide data like navigation categories with caching, user-specific notifications, and cart counts. The caching strategy reduces database hits by caching category data for 5 minutes.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from django.core.cache import cachefrom django.conf import settingsfrom datetime import datetime, timedeltadef site_context(request):"""Provides global template variables for site-wide data."""context = {'site_name': getattr(settings, 'SITE_NAME', 'Capypad'),'current_year': datetime.now().year,}cached_categories = cache.get('nav_categories')if cached_categories is None:from .models import Categorycached_categories = Category.objects.filter(is_active=True,parent__isnull=True).only('id', 'name', 'slug', 'icon').order_by('sort_order')[:10]cache.set('nav_categories', list(cached_categories), 300)context['nav_categories'] = cached_categoriesif request.user.is_authenticated:context['user_notifications'] = get_user_notifications(request.user)context['cart_item_count'] = get_cart_count(request.user)return contextdef get_user_notifications(user, limit=5):"""Retrieve unread notifications for authenticated user."""from .models import Notificationreturn list(Notification.objects.filter(user=user,is_read=False,created_at__gte=datetime.now() - timedelta(days=7)).values('id', 'title', 'message', 'notification_type')[:limit])def get_cart_count(user):"""Get current shopping cart item count."""from .models import Cartreturn Cart.objects.filter(user=user, is_active=True).count()
django
Breakdown
1
def site_context(request):
Context processor function receiving HttpRequest object
2
cached_categories = cache.get('nav_categories')
Try to retrieve categories from cache
3
if cached_categories is None:
Cache miss - fetch from database and cache result
4
cache.set('nav_categories', list(cached_categories), 300)
Cache result for 300 seconds (5 minutes)
5
if request.user.is_authenticated:
Check if user is logged in before loading user-specific data
6
context['user_notifications'] = get_user_notifications(request.user)
Add notifications to context for template rendering
7
created_at__gte=datetime.now() - timedelta(days=7)
Filter notifications from last 7 days only