简体   繁体   English

保存Django外键值

[英]Saving django Foreign Key values

I created a form to add products, but I get an error like ValueError at /product/add_product/ Cannot assign "u'1'": "Product.category" must be a "Category" instance. 我创建了一个添加产品的表单,但在/ product / add_product /处收到类似ValueError的错误,无法分配“ u'1'”:“ Product.category”必须是“ Category”实例。

I am assuming it has something to do with not sending the Foreign Key values right, when i use the print statement i can see the values that are been passed from the form, 我假设这与不正确发送外键值有关,当我使用打印语句时,我可以看到从表单传递的值,

Am i saving the data properly? 我是否正确保存数据?

My 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

My views.py 我的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')

EDIT: This is how my HTML page form looks like 编辑:这就是我的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>

You are using category as category = post['category'] which will give post['category'] as unicode string with value of id field. 您正在使用category作为category = post['category'] ,它将使post['category']作为具有id字段值的unicode字符串。 Instead of that you can do 除此之外,您可以做

category = Category.objects.get(id=post['category'])

But I would suggest to use modelforms (if you haven't done) to build for form and save the objects which will give you much more functionality for validation, error handling etc. 但是我建议使用模型形式 (如果尚未完成)来构建表单并保存对象,这将为验证,错误处理等提供更多功能。

否。执行查找以查找实际模型,或者在转换为数字后分配给等效的后备字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM