我创建了一个表单来添加产品,但在 /product/add_product/ 处出现类似 ValueError 的错误无法分配“u'1'”:“Product.category”必须是“Category”实例。
我假设它与未正确发送外键值有关,当我使用打印语句时,我可以看到从表单传递的值,
我是否正确保存数据?
我的模型.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=250)
def __unicode__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category)
product = models.CharField(max_length=250)
quantity = models.IntegerField(default=0)
price = models.FloatField(default=0.0)
def __unicode__(self):
return self.product
我的观点.py
def add_product(request):
post = request.POST.copy()
category = post['category']
product = post['product']
quantity = post['quantity']
price = post['price']
new_product = Product(category = category, product = product, quantity = quantity, price = price )
return render_to_response('product/add_product.html')
编辑:这就是我的 HTML 页面表单的样子
<form method="post" action="add_product/">
{% csrf_token %}
<label for="category">Category</label>
<select name="category" id="category">
{% for category in category_list %}
<option> {{ category.id }} </option>
{% endfor %}
</select>
<label for="product">Product</label>
<input type="text" name="product" id="product">
<label for="quantity">Quantitiy</label>
<input type="text" name="quantity" id="quantity">
<label for="price">Price</label>
<input type="text" name="price" id="price">
<input type="submit" value="Add New product" id="create">
</form>