我正在尝试遍历表单字段并将它们存储在数据库中。问题是它始终只是存储的最后一个字段。之前的“被跳过”。我可以通过以下方式处理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模板(我正在“手动”构建我的表单,因为我希望能够通过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))
测试用例步骤:
预期结果:
实际结果:
答案 0 :(得分:7)
您只创建一个catformInstance
实例,然后每次在循环中更改它的值。您正在更新数据库中的一行,而不是每次都创建一个新行。
请改为:
for name in request.POST.getlist('name'):
catform = CategoryForm({'name': name}, instance=Category())
catform.save()
请注意,我们明确传递每个name
而不是整套POST
值;在这种情况下,它只会从name
列表中获取姓氏,然后在下一次迭代中失败,因为请求中不再提供name
。