generated from Code-Institute-Org/gitpod-full-template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontexts.py
36 lines (29 loc) · 991 Bytes
/
contexts.py
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
"""
This is the source file for a custom context processor,
which provides site-level access to various data.
It is made visible to Django by including 'cart.contexts.cart_contents'
in the 'context_processors' list in the project settings.
"""
from django.shortcuts import get_object_or_404
from shop.models import Product
def cart_contents(request):
""" returns cart_items, total & product_count as context """
cart_items = []
total = 0
product_count = 0
cart = request.session.get('cart', {})
for item_id, quantity in cart.items():
product = get_object_or_404(Product, pk=item_id)
total += quantity * product.price
product_count += quantity
cart_items.append({
'item_id': item_id,
'quantity': quantity,
'product': product,
})
context = {
'cart_items': cart_items,
'total': total,
'product_count': product_count,
}
return context