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

**URL:** <https://forum.djangoproject.com/t/how-to-add-item-to-cart-after-the-user-login-django/12631>\
**Category:** Django Internals\
**Created:** [March 16, 2022, 12:39am UTC](https://forum.djangoproject.com/t/how-to-add-item-to-cart-after-the-user-login-django/12631 "2022-03-16T00:39:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![CrBibek](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/crbibek/32/7806_2.png) [@CrBibek](https://forum.djangoproject.com/u/CrBibek)\
**Post date:** [March 16, 2022, 12:39am UTC](https://forum.djangoproject.com/t/how-to-add-item-to-cart-after-the-user-login-django/12631/1 "2022-03-16T00:39:14Z")

</div>

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)
    try:
        
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)
        )
    cart.save()

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

```

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

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 16, 2022, 2:02am UTC](https://forum.djangoproject.com/t/how-to-add-item-to-cart-after-the-user-login-django/12631/2 "2022-03-16T02:02:27Z")

</div>

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?
