【问题标题】:How to fix add to cart functionality in django?如何修复 django 中的添加到购物车功能?
【发布时间】:2022-01-11 16:52:10
【问题描述】:

我正在构建一个电子商务平台,我想在网站中创建添加到购物车的功能。但由于某种原因,产品 ID 显示为空。 这是代码: models.py

class Products(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    title = models.CharField(max_length = 255)
    product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100)
    description = models.TextField()
    price = models.FloatField(max_length= 5)

class Cart(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    products = models.ForeignKey(Products, on_delete = models.CASCADE)

views.py

def add_cart(request):
    product_id = Products.id
    new_product = Cart.objects.get_or_create(id=product_id, user=request.user)
    return redirect('/')

模板

<div class="product-wrapper">
      <h1 style="font-size:24px">{{product.title}}</h1>
      <div class="product-price">
        <p style="text-decoration-line:line-through;">$ {{product.price}}</p>
<a href="{% url 'add-product' product.product_id %}">Add to cart<a>
          </div>

当我尝试单击此链接时,它给了我这个错误:Field 'id' expected a number but got . 任何建议都会很有帮助。
谢谢

【问题讨论】:

  • product_id = Products.id 没有意义:您应该通过 URL 或通过 POST 参数提交 id。
  • 我尝试通过另一种方法提交它,但它也不起作用。
  • 分享发出请求的表单。
  • 我已添加发出请求的模板。这是一个详细视图页面,而不是在 for 循环中。
  • urls.py。您似乎使用了 add_cart 以外的其他视图。

标签: django django-views


【解决方案1】:

最后,我解决了这个问题。
view.py

def add_to_cart(request, slug):
    products = Products.objects.get(slug=slug)
    ncart = Cart.objects.create(user=request.user, products=products)
    ncart.save()
    return redirect('/')

模板

<div class="product-wrapper">
      <h1 style="font-size:24px">{{product.title}}</h1>
      <div class="product-price">
        <p style="text-decoration-line:line-through;">$ {{product.price}}</p>
<a href="{% url 'add-to-cart' product.slug %}">Add to cart<a>
          </div>

urls.py

path('cart/add/<slug:slug>', views.add_to_cart, name = 'add-to-cart')

【讨论】:

    【解决方案2】:

    考虑到您已经拥有 Products 实例,在这种情况下

    直接查询如下:

    new_product = Cart.objects.get_or_create(products=Products)
    

    如果你想从 product_id 查询,这样做:

    product_id = Products.pk
    new_product = Cart.objects.get_or_create(products_id=product_id)
    

    此外: request.user 包含一个字典,你不能直接将它传递给查询。并且用户字段具有名称购买者,因此像这样更改该查询:

    product_id = Products.pk
    new_product = Cart.objects.get_or_create(products=Products, buyer_id=request.user['pk'])
    

    【讨论】:

    • 字段 'id' 需要一个数字,但得到 。我也使用这种方法得到同样的错误
    • 从过滤器中移除 id。如答案所示直接添加字段名称。
    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 2022-11-24
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多