How to add item to cart after the user login ? #django

Hello everyone, I’m completely new to Django and I tried to create a simple eCommerce web application. In my code, when the user is not logged, items are easily added to the cart and displayed to the web application but when the same user logged into the application and tries to add the item to the cart it is not displayed in the frontend but the item is added to user from backend.

I tried the logic

if user.is_authenticated

but I was not able to succeed.

from carts.models import Cart, CartItem

def add_cart(request, product_id):
    product = Product.objects.get(id=product_id)
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)

        cart_item = CartItem.objects.get(product=product, cart=cart)
        cart_item.quantity += 1
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product = product,
            quantity = 1,
            cart = cart,
    return redirect('cart')

This is Django code adding items to the cart before the user login.

Please post the complete view that is not working for you.

Note: You’re saying that it’s adding the data to the cart but not being displayed. If it’s being added to the cart, then this likely isn’t the view having the issue - it’s more likely going to be the view being redirected to upon submission.

How are you associating a Cart with a user? (What identifies a Cart with Person X instead of Person Y?)

Also, what are you using for the front end? Is it just Django templates, or is it some front-end framework such as Vue or React?