16. Cart - user with login

As previously mentioned, our cart will feature two primary structures tailored for both logged-in and non-logged-in users.

To explore the cart functionality, it is essential to first instantiate a client object, as this will serve as the primary interface for the cart operations. For this scenario, we will employ the admin user's credentials to generate the client object.

The User is created throught Django's authetication interface (in this case one for the admin account was already created)

For clarity, we will add the __str__ function to the Client, Order, and ItemOrdered classes to display appropriate text representations on the admin page.

models.py
def __str__(self) :
        return str(self.email)

Next, we will modify the cart function within the new_context.py file to retrieve the quantity of ordered items of an authenticated user:

The provided function cart determines the number of products in a user's cart and returns this value. It first checks if the user is authenticated. If authenticated, it retrieves the associated Client object (due to a one-to-one relationship). Then, it either gets an existing Order or creates a new one for the client. By filtering the OrderedItem objects associated with the order, it calculates the total quantity of products in the cart by summing the quantities of each ordered item. Lastly, it returns this total as a dictionary value associated with the key "product_amount_cart".

Manually adding orders for testing
After implementing this change, the quantity of ordered products will be accurately displayed next to the cart.

Last updated