How to save products in the cart after logout

Hello Django people, i need some help.

I am following a course on Udemy, and i am stuck on this issue. Course is good, but the author can’t help unfortunately.

I have two apps.
Accounts and Dashboard.
In the Accounts app i have defined a custom user and imported it into settings.py.

from django.db import models

# define custom user

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    email = models.EmailField(unique=True, max_length=50)
    username = models.CharField(unique=True, max_length=20)

    note = models.TextField(max_length=200, null=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def __str__(self):
        return self.email


Users can register and and here is the login view


def login_view(request):
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            # authenticate user
            user = authenticate(
                request,
                email = form.cleaned_data['email'],
                password = form.cleaned_data['password']
            )

            # does the user exist
            if user is not None:
                login(request, user)
                messages.success(request, 'You are logged in now!')
                return redirect('dashboard:dashboard')
            else:
                # change css to error
                messages.error(request, 'Invalid login')
    else:
        form = UserLoginForm()
    
    context = {
        'form': form,
    }
    return render(request, 'accounts/login.html', context)

Then, in the Shop app i have context_processors.py, cart.py and all views that are needed, with ajax for cart operations.

Cart.py

from decimal import Decimal
from .models import Product

class Cart():
    # create a session for the user
    def __init__(self, request):
        self.session = request.session
        # returning user - obtain his exsisting session
        cart = self.session.get('session_key')        
        # new user - create new session 
        if 'session_key' not in request.session:
            cart = self.session['session_key'] = {}        
        self.cart = cart
    
    def add(self, product, product_qty):

        product_id = str(product.id)
        
        if product_id in self.cart:
            self.cart[product_id]['qty'] = product_qty
        else:
            self.cart[product_id] = {'price': str(product.price), 'qty': product_qty}
        
        self.session.modified = True
    
    # function to save number of products in header cart icon
    # number of products in shopping cart
    def __len__(self):
        return sum(item['qty'] for item in self.cart.values())


    #### CART PAGE ####
    # iterate thru products on cart page
    def __iter__(self):
        # get all product ids that are added to cart
        all_product_ids = self.cart.keys()

        # get all products whose id matches with id of the products in cart
        # import Decimal and Product model
        products = Product.objects.filter(id__in=all_product_ids)

        # copy the instance of session data
        #cart = self.cart.copy()

        # instance copy moze i ovako
        import copy
        cart = copy.deepcopy(self.cart)

        # loop thru products added and add some data
        for product in products:
            cart[str(product.id)]['product'] = product
        
        # get prices for products
        for item in cart.values():
            item['price'] = Decimal(item['price'])
            # get total price
            item['total'] = item['price'] * item['qty']
            # get final result of calculations
            yield item
    
    # get total cart price of all products added to cart
    def get_total(self):
        return sum(Decimal(item['price']) * item['qty'] for item in self.cart.values())
    
    def update(self, product, qty):
        product_id = str(product)
        product_quantity = qty

        if product_id in self.cart:
            self.cart[product_id]['qty'] = product_quantity
        
        self.session.modified = True

   
    def delete(self, product):
        product_id = str(product)
        if product_id in self.cart:
            del self.cart[product_id]
        
        self.session.modified = True
    

I don’t know if this is enough, if i need to send something more i will.

The issue is that when i test like a logged in user, add a few products in the cart, then logout, then log back in, the cart goes to zero.

Second issue is that when i test as a guest user, i put some products in the cart, i login, the cart is saved but the session id changes.

Hope somebody can help :slight_smile:

Thanks!