gpt4 book ai didi

python - 每次我注销并重新登录时,都会创建一个新购物车,Django Cart App

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:33 25 4
gpt4 key购买 nike

我是 Django 新手!我试图让未经身份验证的用户将产品添加到购物车。当他们登录并刷新时,购物车与用户关联。但问题是针对经过身份验证的用户。当经过身份验证的用户注销并重新登录时,将为他创建一个新的购物车。这是我的功能,它检查我是否需要制作一个新的购物车或获取现有的购物车。

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:
cart_obj.user = request.user
cart_obj.save()
else:
cart_obj = Cart.objects.create(user=request.user)
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj

最佳答案

您应该将用户添加到过滤器中,以确保用户获得他们的购物车,因为您将用户链接到了购物车。

def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
filter_kwargs = {'id': card_id}
if request.user.is_authenticated():
filter_kwargs.update({'user': request.user})

qs = self.get_queryset().filter(**filter_kwargs)
if qs.count() == 1:
new_obj = False
cart_obj = qs.first()
if request.user.is_authenticated() and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()
else:
cart_obj = Cart.objects.create(user=request.user)
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj

您还可以查看模型上的 django 辅助方法,它可能适合您;

def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
filter_kwargs = {'id': card_id}
if request.user.is_authenticated():
filter_kwargs.update({'user': request.user})

cart_obj, created = Cart.objects.get_or_create(**filter_kwargs)

if request.user.is_authenticated() and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()

request.session['cart_id'] = cart_obj.id
return cart_obj, created

查看此处的文档; https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create

关于python - 每次我注销并重新登录时,都会创建一个新购物车,Django Cart App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48531522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com