我正在尝试遍历表单字段并将它们存储在数据库中。问题是它总是只有最后一个被存储的字段。前面的被“跳过”。我可以通过以下方式处理 Django 中的表单吗?
模型.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
表格.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>
视图.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 个输入字段中插入以下值:value1、value2、value3
- 按下提交按钮
预期结果:
- 所有 3 个值都存储在数据库中
实际结果:
- 只有最后一个值 (value3) 存储在数据库中