我试图允许客户将商品(CartItem)添加到购物车中。 CartItem通过ForeignKey链接到我的Products模型。我已通过管理员创建了产品列表。
我能够在.html页面上填写表单(AddItemForm)并显示可用产品列表。但是当我选择一个项目时,选择数量并点击“添加项目”,我收到以下错误:
无法指定" u' 2'":" CartItem.product"必须是"产品"实例
我不知道哪里出错了。
models.py
class CartItem(models.Model):
cart = models.ForeignKey('Cart', null=True, blank=True)
product = models.ForeignKey(Product)
quantity = models.IntegerField(default=1, null=True, blank=True)
line_total = models.DecimalField(default=0.00, max_digits=1000, decimal_places=2)
notes = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
try:
return str(self.cart.id)
except:
return self.product.title
views.py
def add_to_cart(request):
request.session.set_expiry(120000)
try:
the_id = request.session['cart_id']
except:
new_cart = Cart() # creates brand new instance
new_cart.save()
request.session['cart_id'] = new_cart.id # sets cart_id
the_id = new_cart.id
cart = Cart.objects.get(id=the_id) # use the cart with the 'id' of the_id
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
form = AddItemForm(request.POST or None)
if request.method == "POST":
qty = request.POST['quantity']
product = request.POST['product']
cart_item = CartItem.objects.create(cart=cart, product=product)
cart_item.quantity = qty
cart_item.save()
return HttpResponseRedirect('%s'%(reverse('cart')))
context = {
"form": form
}
return render(request, 'create_cart.html', context)
forms.py
from django import forms
from .models import Cart, CartItem
from products.models import Product
class AddItemForm(forms.ModelForm):
product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.Select)
quantity = forms.IntegerField()
class Meta:
model = CartItem
fields = ["product", "quantity"]
html的
{% extends "base_site.html" %}
{% block content %}
<form method="POST" action="{% url 'add_to_cart' %}">
{% csrf_token %}
<table>
<thead>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
</thead>
<tr>
<td>{{ form.product }}</td>
<td>{{ form.quantity }}</td>
<td></td>
<td><input type="submit" value="Add Item" /></td>
</tr>
</table>
</form>
{% endblock %}
答案 0 :(得分:2)
问题出在那一行:
cart_item = CartItem.objects.create(cart=cart, product=product)
create
方法期望product
为Product
实例,您传递的是字符串(u'2'
)。
使用product_id
代替product
:
product_id = int(request.POST['product'])
cart_item = CartItem.objects.create(cart=cart, product_id=product_id)
这样可以解决代码问题,但您应该使用AddItemForm
而不是直接从POST数据创建CartItem
:
form = AddItemForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save() # Takes care of saving the cart item to the DB.
return HttpResponseRedirect(reverse('cart'))