无法分配 "u'2'":"CartItem.product" 必须是 "Product" 实例

Cannot assign "u'2'": "CartItem.product" must be a "Product" instance

我正在尝试让客户将商品 (CartItem) 添加到他们的购物车。 CartItem 通过 ForeignKey 链接到我的产品模型。我已经通过管理员创建了一个产品列表。

我能够获取要填充到 .html 页面上的表单 (AddItemForm) 并显示可用产品列表。但是当我 select 一个项目,选择数量并点击 'Add Item',我得到以下错误:

无法分配 "u'2'":"CartItem.product" 必须是 "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 %}

问题出在那一行:

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'))