Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cart Not working properly #1

Open
404shades opened this issue Jan 2, 2018 · 2 comments
Open

Cart Not working properly #1

404shades opened this issue Jan 2, 2018 · 2 comments

Comments

@404shades
Copy link

After logging out and then logging in again creates a new session that's why a new cart object is created every time hence after logging in again user do not get their previous updated cart instead empty.

@vykuntaharsha
Copy link

yes, I have raised this in Udemy lecture, I will post my code here also, see if this helps

class CartManager(models.Manager):
    def new_or_get(self, request):
        cart_id = request.session.get("cart_id", None)
        qs = self.get_queryset().filter(id=cart_id)
        if qs.count() == 1:
            new_obj = False
            cart_obj = qs.first()
            if request.user.is_authenticated() and cart_obj.user is None:
                user_cart = self.model.objects.filter(user=request.user).first()
                if user_cart is not None:
                    cart_obj.products.add(*user_cart.products.all())
                    cart_obj.user = request.user
                    cart_obj.save()
                    user_cart.delete()
                else:
                    cart_obj.user = request.user
                    cart_obj.save()
        else:
            cart_obj = Cart.objects.new(user=request.user)
            new_obj = True
            request.session['cart_id'] = cart_obj.id
        return cart_obj, new_obj
 
    def new(self, user=None):
        user_obj = None
        if user is not None:
            if user.is_authenticated():
                cart_obj = self.model.objects.filter(user=user).first()
                if cart_obj is not None:
                    return cart_obj
                user_obj = user
        return self.model.objects.create(user=user_obj)

@igortosic-easymind
Copy link

If you want to return just a model instance, use get().
Edit this part of the code: cart_obj = qs.first() => cart_obj = qs.get()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants