我創建了一個表單來添加產品,但出現如下錯誤:ValueError at/product/add_product /無法分配「u'1'」:「Product.category」必須是「Category」實例。保存django外鍵值
我假定它是與不發送外鍵值對的,當我使用打印聲明,我可以看到那些從表單傳遞的值,
難道我節省數據正確嗎?
我model.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
我views.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>
嗯,我現在沒有得到錯誤,但我的數據沒有得到保存,任何原因?我應該做「new_product.save()」? – shabeer90
是的,我不得不做「new_product.save()」:D – shabeer90