这里我要将新项目添加到我的产品表(db)中。但即时面临着像快照一样的错误 我在我的产品表中将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')
这是模型
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)
in add_product1.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>
答案 0 :(得分:0)
你应该使用ModelForm,它有一些有用的工具,如验证,自动表单创建等......:https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/
ModelForm会将字段Vendor
放入<select>
输入。
答案 1 :(得分:0)
这是答案
我们应该在值中做id
id : <select name='my_options' >
{% for Vendor in obj %}
<option value='{{Vendor.id}}' >{{Vendor.name}}</option>
{%endfor%}
</select><br />
然后它顺利地切换外键