After building the product catalog, the next step is to create a shopping cart that allows users to select the products that they want to purchase.
- [Instructor] Hi. We're now at the third video of this section, Building a Shopping Cart. Previously, we looked at creating an online shop project. In this video, we'll use Django Sessions and learn about session settings. We'll also look into session expiration and then store shopping carts in sessions. After building the product catalog the next step is to create a shopping cart that will allow users to select the products that we want to purchase. A shopping cart allows users to select the products they want and store them temporary while they browse the site, until they eventually place an order.
The cart has to be persisted in the session so that the cart items are kept during the user's visit. Here, we'll use Django's session framework to persist the cart. The cart will be kept in the session until it finishes or the user checks out of the cart. We'll also need to build additional Django models for the cart and its items. Let's see how to use Django sessions. Django provides a session framework that supports anonymous and user sessions. The session framework allows you to store arbitrary data for each visitor.
Session data is stored on the server side and cookies contain the session ID unless you use the cookie based session engine. The session middleware manages sending and receiving cookies. The default session engine store session data in the database but as you will see next, you can choose between different session engines. To use sessions, you have to make sure that the MIDDLEWARE_CLASSES settings of your project contains django.contrib.sessions.middleware.SessionMiddleware.
This middlewear manages sessions and is added by default when you create a new project using the start project command. The session middleware makes the current session available in the request object. You can access the current session using the request.session. By utilizing it similarly to a Python dictionary to store and retrieve session data. The session dictionary accepts any Python object by default that can be serialized into JSON. So, this is how you can set a variable in the session, retrieve a session key and delete a key you stored in the session.
As you saw, we just treated a request.session like a standard Python dictionary. When users log into the site their anonymous session is lost and a new session is created for the authenticated users. If you store items in an anonymous session that you need to keep after users log in, you need to copy the old session data into the new session. Now, we move forward to session settings. There are several settings you can use to configure sessions for your project. The most important is session_engine.
This setting allows you to set the place where sessions are stored. By default, Django stores sessions in the database using the session model of the Django.contrib.sessions application. Here are a few options for storing session data, offered by Django. The database sessions. With this session data is stored in a database. This is the default session engine. Next, is file based sessions. By using it, session data is stored in the file system. Then comes cached sessions.
This is used to store session data in a cached backend. You can specify cached backends using the caches setting. Storing session data in a cache offers best performance. We also have cached database sessions. By this, session data is stored in a write through cache and database reads, only use the database if the data is not already in the cache. And the last one is cookie based sessions. This enables to store session data in the cookies that are sent to the browser.
For best performance, use a cache based session engine. Django supports Memcached and there are other third party cached backends for redis and other cache systems. You can customize sessions with other settings. Here are some of the important session related settings. First comes, session cookie age. This is the duration of session cookies, in seconds. The default value is 1,209,600. That is two weeks.
Then we have session cookie domain. This domain is used for session cookies. Set this to .mydomain.com to enable cross domain cookies. The third one, session cookie secure is a boolean indicating that the cookie should only be sent if the connection isn't HTTPS connection. Next is session expire at browser close. Which is a boolean indicating that the session has to expire when the browser is closed. And the last one is, session save every request. This is a boolean that if true, will save the session to the database on every request.
The session expiration is also updated each time. You could find all session settings at, .startdjangoproject.com. Now we talk about session expiration. You can choose to use browser length sessions or persistent sessions, using the session expire at browser close setting. This is set to false by default, forcing the session duration to the value stored in the session cookie age setting. If you set session expire to true, the session will expire when the user closes the browser and the session cookie age setting will not have any effect.
You can use the set_expiry method of request.session to overwrite the duration of the current session. Let's learn to store shopping carts in sessions. So, we need to create a simple structure that can be serialized to JSON for storing cart items in a session. The cart has to include these data for each item contained in it. ID of a product instance and the quantity selected for this product. It should also contain the unit price for this product. Since product prices may vary, we take the approach of storing the product's price along with the product, itself, when added to the cart.
By doing so, we keep the same price that users saw when they added the item to the cart. Even if the product's price is changed afterwards. Now we have to manage creating carts and associate them with sessions. The shopping cart has to work in an organized manner. When a cart is needed, we check if a custom session key is set. If no cart is set in the session, we create a new cart and save it in the cart session key. For successive requests, we perform the same check and get the cart items from the cart session key. We retrieve the cart items from the session and their related product objects from the database.
Now, we edit these settings.py file of our project and add these settings to it, at the bottom of the code. CART_SESSION_ID = cart. This is the key that we're going to use to store cart in the user session. Since Django sessions are per visitor, we can use the same cart session for all sessions. Let's create an application for managing shopping carts. Open the terminal and create a new application. Run this command from the project directory, python manage.py startapp cart.
Then, edit the settings.py file of your project and add the cart to the installed app setting, as we do here. And save the file. Next, we create a new file inside the cart application directory and name it Cart.py. Add this code to it and save. This is the cart class that will allow us to manage the shopping cart. We require the cart to be initialized with a request object. We store the current session using a self.session = request.session to make it accessible to other methods of the cart class.
First, we try to get the cart from the current session using self.session.get method. If no cart is present in the session, we set an empty cart by just setting an empty dictionary in the session. We expect our cart dictionary to use product IDs as keys and a dictionary with quantity and price as value for each key. By doing so, we can guarantee that a product is not added more than once in the cart. We can also simplify the way to access any cart item data. Let's create a method to add products to the cart or update their quantity.
So, we add the add method and also the save method to the cart class. The add method, takes these parameters. The product instance to add or update in the cart. Quantity, which is an optional integer for product quantity. This defaults to one. And the third one is update quantity which is a boolean that indicates whether the quantity needs to be updated with the given quantity. For true, or the new quantity needs to be added to the existing quantity for the boolean value false.
We use the product ID as a key in the cart contend dictionary. We convert the product ID into a string because Django uses JSON to serialize session data and JSON only allows string names. The product ID is the key and the value that we persist is a dictionary with quantity and price for the product. The product price is converted from decimal into string in order to serialize it. Finally, we call the save method to save the cart in the session. The save method saves all the changes in the cart in the session and marks the session as modified using the session.modify = true.
This tells Django that the session has changed and needs to be saved. We also need a method for removing product from the cart. Hence, we add this method to the cart class. The remove method removes a given product from the cart dictionary and calls the save method to update the cart in the session. Now, we have to iterate through the items contained in the cart and access the related product instances. To do so, you can define an ITER method in your class. And add this method to the cart class.
In the iter method we retrieve the product instances that are present in the cart to include them in the cart items. Finally, we iterate over the cart item converting the item's price back into decimal and add a total_price attribute to each item. Now we can easy iterate over items in the cart. Here we also need a way to return the number of total items in the cart. When the len function is executed on an object, Python calls its len method to retrieve its length. Now we define a customer len method to return the total number of items stored in the cart.
So we add this len method to the cart class. We return the sum of the quantities of all the cart items and also add the get total price method to calculate the total cost for the items in the cart. Finally, we add a method to clear the cart session. Our cart class is now ready to manage shopping carts. Cool. In this video we've built a shopping cart. In the next video, we'll learn to create shopping cart views.
Note: This course was created by Packt Publishing. We are pleased to host this training in our library.
- Creating an online shop project
- Registering customer orders
- Managing payments and orders
- Integrating a payment gateway
- Extending the online shop
- Creating a coupon system
- Translating Python code