【发布时间】: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