Create Account/Login
← Previous: Part 2 | Render cart Total Next: Part 4 | cookieCart() Function →
Part 3 | Build Order

Overview:

Now its time to build a dictionary representation of a real order. Remember, a guest user never actually creates an order until checkout, everything is stored in their browsers cookies.

Our job is to create an object representation or a real order, including items so we can render this data out in the template without adding any extra logic in the template.

What we will build

We will add on to our loop from the last part and set more values on our order such as "get_cart_total", "shipping" and even build out an entire list of objects representing cart items.

Output


Step 1 | Order Totals
00:24:23

We covered getting the total item count for our cart in the last step, now we will get the cart price total (get_cart_total).

Query Product

First we will add on the loop in our "cart" view and query the product so we can get the price. Rember that "i" in our loop is the product id.

Get and set totals

Once we have the product we can set the value of total by multiplying the product price by the quantity.

Go ahead and add the total (+=) to order['get_cart_total']

Do the same for order['get_cart_items'] with the quantity since we need this value in the order also.

View Source Code


Step 2 | Items Queryset
00:26:50

Just like we had to create a representation of an order with a dictionary we will need to do the same for items in our cart.

In order for our cart and checkout page to render these items and all the proper information, we need it to look exactly like a real item so our template doesn't know the difference.

 

In each iteration of the loop for items in our cart, we will create an item object and append to our items list. 

The item object will contain ALL the same attributes that our OrderItem model does. As you build this page look closely at all the code I provide with this.

Now if we refresh our cart page we should see all the items rendered in our table.

View Source Code


Step 3 | Shipping Information
00:31:30

Because this data will be the same across all pages, let's add in a check for shipping information.

Just underneath where we append the item to the items list, let's query the products "digital" attribute and Django the value of "shipping" to try if one of the items is NOT a digital item.

View Source Code


Step 4 | Product Does Not Exist
00:32:23

A potential problem we can face is a user adding a product to their cart and in the time frame it takes the user to checkout, let's say the admin removes the item from the database.

This means we will query a product with bad id. We can fix this by adding a "try/except" block within our loop and ignoring this issue.

View Source Code

← Previous: Part 2 | Render cart Total Next: Part 4 | cookieCart() Function →