django来宾用户添加到购物车

时间:2020-07-06 08:43:49

标签: django django-models django-rest-framework django-views

class Product(models.Model):
    title           = models.CharField(max_length=120)
    slug            = models.SlugField(blank=True)
    description     = models.TextField()
    price           = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
    image           = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
    featured        = models.BooleanField(default=False)
    # quantity        = models.IntegerField(default=1, null=True, blank=True)
    active          = models.BooleanField(default=True)
    timestamp       = models.DateTimeField(auto_now_add=True)

class OrderItem(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)


class Cart(models.Model):
    user        = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE)
    products    = models.ManyToManyField(OrderItem, blank=True)
    subtotal    = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    total       = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
    updated     = models.DateTimeField(auto_now=True)
    timestamp   = models.DateTimeField(auto_now_add=True)

"""i am trying to create a ecom website and trying to add products in cart without login 
   the below code works with login user as request.user how to change it with guest user 
"""

def add_cart(request, slug):
    item = get_object_or_404(Product,slug=slug)
    order_item ,created = OrderItem.objects.get_or_create(
        user=request.user,
        item =item,
    )
    print(order_item)

    order_qs = Cart.objects.filter(user=request.user)
    if order_qs.exists():
        order= order_qs[0]
        # check if the order item is in the order
        if order.products.filter(item__slug=item.slug).exists():
            order_item.quantity+= 1
            order_item.save()
            print("1")
        else:
            order.products.add(order_item)
    else:
        order = Cart.objects.create(
            user=request.user
        )
        order.products.add(order_item)
        print("done")
    return redirect("cart:home")

我正在尝试创建一个ecom网站,并尝试在没有以下代码的情况下在购物车中添加产品,但该代码仅适用于具有request.user的登录用户。用户如何与来宾用户进行更改并执行添加购物车和数量 以访客用户身份访问产品

2 个答案:

答案 0 :(得分:0)

您可以在数据库中创建一个代表来宾用户的特定用户,然后将购物车分配给该用户。但是,我不建议这样做。

我假设您希望访客能够保存他们的购物车。您也可以通过设置包含购物车数据的cookie来实现。您不需要任何后端,因为可以使用javascript构建。

答案 1 :(得分:0)

您需要使用Django Sessions Framework实现此目的。 Django Sessions Framework

我不确定这是否是最好的解决方案,但是以下代码对我来说很有吸引力。如果不想使用JavaScript,而只想坚持Django Sessions Framework,请使用此方法。

在购物车模型中:

class Cart(models.Model):
  user        = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE)
  products    = models.ManyToManyField(OrderItem, blank=True)
  subtotal    = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
  total       = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
  updated     = models.DateTimeField(auto_now=True)
  timestamp   = models.DateTimeField(auto_now_add=True)
  ordered     = models.BooleanField(default=False)
  session_key = models.CharField(max_length=40, null=True)

在您的视图中。py

def add_cart(request, slug):
if request.user.is_authenticated:
    item = get_object_or_404(Product,slug=slug)
    order_item ,created = OrderItem.objects.get_or_create(
        user=request.user,
        item =item,
    )
    print(order_item)

    order_qs = Cart.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order= order_qs[0]
        # check if the order item is in the order
        if order.products.filter(item__slug=item.slug).exists():
            order_item.quantity+= 1
            order_item.save()
            print("1")
        else:
            order.products.add(order_item)
    else:
        order = Cart.objects.create(
            user=request.user
        )
        order.products.add(order_item)
        print("done")
    return redirect("cart:home")
else:
    item = get_object_or_404(Product,slug=slug)
    order_item ,created = OrderItem.objects.get_or_create(
        user=None,
        item =item,
    )
    print(order_item)

    order_qs = Cart.objects.filter(user=None, ordered=False, session_key=request.session.session_key)
    if order_qs.exists():
        order= order_qs[0]
        # check if the order item is in the order
        if order.products.filter(item__slug=item.slug).exists():
            order_item.quantity+= 1
            order_item.save()
            print("1")
        else:
            order.products.add(order_item)
    else:
        order = Cart.objects.create(
            user=None, session_key=request.session.session_key
        )
        order.products.add(order_item)
        print("done")
    return redirect("cart:home")

进一步参考: Thanks to Todor Django: Anonymous session & "temporary" one-to-one related model?