Reputation: 397
I am creating a Django middleware that manages a 'shopping cart' with sessions. I was able to successfully modify the session data like so:
class ShoppingCartMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Ensure shopping cart exists
if request.session.get('shopping_cart') is None:
request.session['shopping_cart'] = {'items': []}
return self.get_response(request)
I now need to modify the template context so that my templates can have access to certain information about the shopping cart (number of items, etc). I looked at context processors, but context processors are not able to view the session or even the current context.
I tried using the process_template_response
hook like so:
def process_template_response(self, request, response):
response.context_data['cart_num_items'] = len(request.session['shopping_cart']['items'])
return response
but apparently when the hook is executed, response.context_data
is None
.
Does anyone know how to edit the template context with middleware? Any help would be appreciated.
Upvotes: 5
Views: 2337
Reputation: 59184
You don't have to modify the context as you have access to the request
object itself. Just add a new attribute:
class ShoppingCartMiddleware:
...
def __call__(self, request):
shopping_cart = {'product': 'Blah', 'id': 123}
request.shopping_cart = shopping_cart
...
then use it in your template
{{ request.shopping_cart.product }}
Upvotes: 9