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.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With