2015-05-03 44 views
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 %} 

回答

1

问题在于该行:

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')) 
相关问题