Create Account/Login
← Previous: Part 1 | Set Cookie's Next: Part 3 | Build Order →
Part 2 | Render cart Total

Overview:

In this step, we are going to cover retrieving our browsers cart values in our Django views and setting/rendering out the total for the navigation bar.

Turn this 

Into This


Step 1 | Query Cart in views.py
00:20:25

Now that we have added some data to our browsers cookies; the way we render cart data for guest users is to retrieve the cookie data in our backend (views) and build a replica of an order.

Remember the cookie we set only stores product id's and quantity. We need to work with this data to eventually build an entire cart inside of our views. But, for now we just want to total up the items in our cart and update the "get_cart_total" in our "order" dictionary that we have in each view.

Get Cookies in view

We can retrieve what's in our browsers cookies by using request.COOKIES['cart'] and json.loads() to parse the data because currently it is a string value.

Inside of our "views.py", let's start by adding this logic inside the "cart" view just after "else" in our conditional so we only get this data when the visitor is NOT logged in.

Open up your cart page and make sure the cart prints successfully.

Cart does not exist error.

One thing all first time visitors will see if we do not fix this is a nasty error since they will have no cookie cart if this is their first time viewing our website.

We can fix this by using a try/except statement and create an empty cart to work with if one does not exist.

View Source Code


Step 2 | Build Cart Total
00:23:10

Now that we have our "cart object", we want to find the total number of items the guest visitor has in their cart and update our order objects ‘get_cart_items’ attribute.

For this we can simply loop through our cart dictionary and add the total quantity of each item. 

When looping through a dictionary, I will represent the "key". Which, in our case, is the product id.

This loop will query the quantity of each item in our cart and add to the value of "cartItems" therefore giving us the total of all items + quantity in the entire cart.

Now if we are logged out and add some items to our cart; we should see something like this in our cart page navbar.

At this point, we only added this logic to our "cart" view so it will still show "0" on all other pages. We will add a little more to our order within the "cart" view in the next part and then make this work across the entire website.

View Source Code

← Previous: Part 1 | Set Cookie's Next: Part 3 | Build Order →