所以我在forms.py文件中有一个表单类,我将用它来创建一个具有可变数量表单的表单集(客户端将设置要显示的表单数)。
表单类是这样的:
forms.py
from django import forms
class example(forms.Form):
CHOICES = [('choice1', 'choice1'), ('choice2', 'choice2')]
field1 = forms.IntegerField()
field2 = forms.DateTimeField()
field3 = forms.ChoiceField(choices = CHOICES)
然后在我的views.py文件中我有这样的东西:
views.py
from myproject.forms import example
from myproject.models import example_model
from django.forms.formsets import formset_factory
from django.http.response import HttpResponseRedirect
from django.shortcuts import render_to_response
def add_example_form(request, model_id, num_forms): # the num_forms is passed previously from another view via URL
mymodel = example_model.objects.get(pk = model_id) #I'll use the formset for filling sa field of a model which couldn't be filled in the creation of the model for whatever reason
data1 = None
data2 = None
data3 = None
data_total = []
exampleFormset = formset_factory(example, extra = int(num_forms))
if request.method == 'POST':
formset = exampleFormset(request.POST)
if formset.is_valid():
for form in formset:
data1 = form.cleaned_data['field1']
data2 = form.cleaned_data['field2']
data3 = form.cleaned_data['field3']
data_total.append([data1, data2, data3])
#Then I save these fields into a field of a model that I have saved on my main database
mymodel.somefield = data_total
mymodel.save()
return HttpResponseRedirect('/someURL/')
else:
raise Exception('The introduced fields are wrong!')
else:
formset = exampleFormset()
return render_to_response('someURL/example.html',{'formset': formset}, context_instance = RequestContext(request))
在我的html模板文件中,我使用以下格式调用formset:
example.html的
<html>
<body>
<h2>Fill the forms:</h2>
<form method='post' action=''> {% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }} <br>
{% endfor %}
<p><input type='submit' value='Submit'/></p>
</form>
</body>
</html>
因此,当我运行服务器并且我与客户端连接到此视图时,所有似乎都正常工作,它将正确数量的表单加载到is_valid()为True,并且HTTP POST请求似乎没有错误。问题是我从提交的formset获取的信息是错误的:它只获取LAST表单的字段的信息并将其复制到其余表单,但它只发生在DateTimeField和ChoiceField,IntegerField字段是正确的。 例如,这将是我对客户的看法:
填写表格:(表格数量= 2)
field1:1
field2:2001-01-01 01:01:01
field3 :(我们选择&#39; choice1&#39;选择)
field1:2
field2:2002-02-02 02:02:02
field3 :(我们选择&#39; choice2&#39;选择)
提交
当点击提交按钮时,所有过程似乎都没问题,但两个表单的field2和field3中的formset检索的数据是第二个表单中的数据,所以实际上我已经在我的数据库中保存了以下内容: / p>
field1:1
field2:2002-02-02 02:02:02
field3:&#39; choice2&#39;
field1:2
field2:2002-02-02 02:02:02
field3:&#39; choice2&#39;
我无法确定这里的问题在哪里,因为代码很简单,或者如果这是一个已知的django错误(我不这么认为),任何帮助都会非常感激。 提前谢谢。