0
我試圖循環表單域並將它們存儲在數據庫中。問題在於它始終只是最後一個被存儲的字段。以前的「跳過」。我可以通過以下方式處理Django中的表單嗎?如何遍歷表單域並將它們全部存儲在數據庫中?
models.py:
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
user = models.ForeignKey(User, blank=True, null=True)
class Meta:
verbose_name_plural = "Ingredience Categories"
def __unicode__(self):
return self.name
forms.py
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = ('name',)
home.html的模板(我 「手動」 我的buildin形式,因爲我想成爲能夠通過jQuery動態添加更多輸入字段):
<h3>Insert New Categories</h3>
<form action="/" method="post" id="ingr-cat-form">{% csrf_token %}
<p><label for="id_0-name">Name:</label> <input type="text" maxlength="30" name="name" id="id_0-name"></p>
<p><label for="id_1-name">Name:</label> <input type="text" maxlength="30" name="name" id="id_1-name"></p>
<p><label for="id_2-name">Name:</label> <input type="text" maxlength="30" name="name" id="id_2-name"></p>
<input type="submit" name="ingrCatForm" value="Save" />
</form>
views.py:
def home(request):
if request.method == 'POST':
catform = CategoryForm(request.POST, instance=Category()) # store bounded form to catform
catformInstance = catform.save(commit = False) # create instance for further modification, don't commit yet
catformNames = request.POST.getlist('name') # get a list of input values whose element name is "name"
for name in catformNames: # loop through all name elements
catformInstance.name = name # modify form instance; insert current name
catformInstance.save() # save the instance to the database
return HttpResponseRedirect('')
else:
catform = CategoryForm(instance=Category())
context = {'catform': catform}
return render_to_response('home.html', context, context_instance=RequestContext(request))
測試用例步驟:
- 將下面的值在3輸入字段:值1,值2,值3
- 按提交按鈕
預期結果:
- 所有3個值被存儲在數據庫
實際結果:
- 只有最後的值(值3)被存儲在數據庫中
你最好使用formset。 –