0
我试图让客户将一个项目(CartItem)添加到他们的购物车。 CartItem通过ForeignKey链接到我的产品模型。我通过管理员创建了一个产品列表。不能分配“u'2'”:“CartItem.product”必须是“产品”实例
我能够获取表单(AddItemForm)来填充.html页面并显示可用产品的列表。但是,当我选择一个项目,选择数量并点击“添加项目”,我得到以下错误:
无法分配“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 %}