0

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.

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

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

<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>
4

2 に答える 2

2

You are using category as category = post['category'] which will give post['category'] as unicode string with value of id field. 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.

于 2012-10-01T08:18:58.707 に答える
1

No. Either perform a lookup to find the actual model, or assign to the equivalent backing field after converting to a number.

于 2012-10-01T08:15:46.360 に答える