python / intermediate
Snippet
Django Context Processors for Dynamic Template Data
Context processors allow you to inject variables automatically into every template context without manually passing them in each view. They are functions that receive the request object and return a dictionary of variables. This is ideal for global data like site settings, navigation categories, shopping cart status, or user-specific information that should be available across all templates.
snippet.py
python
1
from django.conf import settings\nfrom .models import Category\n\ndef site_info(request):\n return {\n 'site_name': settings.SITE_NAME,\n 'site_version': settings.SITE_VERSION,\n 'debug_mode': settings.DEBUG\n }\n\ndef categories_processor(request):\n categories = Category.objects.filter(is_active=True)\n return {'all_categories': list(categories.values('id', 'name'))}\n\ndef cart_processor(request):\n cart_count = 0\n cart_total = 0\n if request.user.is_authenticated:\n try:\n cart = request.user.cart\n cart_count = cart.items.count()\n cart_total = cart.total_price\n except Cart.DoesNotExist:\n pass\n return {'cart_count': cart_count, 'cart_total': cart_total}
django
Breakdown
1
def site_info(request):
Create a context processor function that receives the request
2
'site_name': settings.SITE_NAME,
Return settings values available in all templates
3
def categories_processor(request):
Query database to fetch active categories
4
return {'cart_count': cart_count, 'cart_total': cart_total}
Return user-specific cart data for every template render