2013-02-26 140 views
-2

這裏我要將新項目添加到我的產品表格(db)中。但在捕捉
面臨這樣的錯誤IM我有我的產品表如何在我的產品表格中添加新項目

VENDOR_ID爲外鍵,這是我view.py

def add1(request): 
     obj = Vendor.objects.all() 
     return render_to_response('add_product1.html',{'obj':  
                obj},context_instance=RequestContext(request)) 


def add_product2(request): 
    if request.method == 'GET': 

     val0 = request.GET.get('options') 
     val1 = request.GET.get('name') 
     val2 = request.GET.get('price') 
     val3 = request.GET.get('category_product') 
     val4 = request.GET.get('quantity') 
     v = Product(Vendor= val0,name=val1,price=val2,category_product=val3,quantity= val4) 
     v.save() 
     return HttpResponseRedirect('/manage_product') 

這是add_product1模型

class Vendor(models.Model): 
    name = models.CharField(max_length=30) 
    address = models.CharField(max_length=100) 
    contact = models.CharField(max_length=100) 
    created_date = models.DateField() 
    class Product(models.Model): 
    Vendor = models.ForeignKey(Vendor) 
    name = models.CharField(max_length=30) 
    price = models.CharField(max_length=40) 
    category_product= models.CharField(max_length=40) 
    quantity = models.CharField(max_length=40) 

。 html

<form action="/add_product2/" method="POST"> 

    id : <select name='options' > 
    {% for Vendor in obj %} 
    <option value='0' >{{Vendor.id}}</option> 
    {%endfor%} 
    </select><br /> 

    Product Name:<input type ='text' name= 'name' value =''></br> 
    Price : <input type ='text' name= 'price' value = ''></br> 
    Category_product :<input type = 'text' name= 'category_product' value = ''></br> 
    Quantity: <input type ='text' name='quantity' value = ''></br> 
    <input type='submit' name='Submit' value='add' /> 
    </form> 
+3

修正格式,向我們展示了模型和發佈完整的錯誤回溯。 – rantanplan 2013-02-26 12:56:32

+0

消息是明確的:'estore_product.Vendor_id可能不是NULL' – Zulu 2013-02-26 13:06:13

+0

如果您在DB中更改了某些東西,則應該在POST中發出請求。 – Zulu 2013-02-26 13:10:09

回答

0

這裏就是答案
我們應該做的ID在值

id : <select name='my_options' > 
{% for Vendor in obj %} 
    <option value='{{Vendor.id}}' >{{Vendor.name}}</option> 
    {%endfor%} 
    </select><br /> 

然後移交外鍵平穩地

0

你應該使用ModelForm,它有一些你sefull工具,如驗證,自動創建表單等...:https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/

ModelForm將字段Vendor置入<select>輸入。

+0

但是很抱歉,現在不能更改我的完整代碼,因爲這是我項目的一部分 – raghu 2013-02-26 13:10:01

+0

ModelForm使用您現有的模型創建表單並保存它以及更多內容,使用它不超過5分鐘。 – Zulu 2013-02-26 13:12:40

相關問題