问题描述
关于django 1.4和formsets,我遇到了一个奇怪的问题:当提交的数据不变时,formset的clean_data字段为空,即使表单本身通过验证。这是一个例子:
forms.py:
class NameForm(forms.Form):
name = forms.CharField(required = False,initial ='Foo')
views.py:
code> def welcome(request):
Formset = formset_factory(NameForm,extra = 1)
如果request.method =='POST':
formset = Formset (request.POST)
print'1.Formset有效?',formset.is_valid()
print'2.Formset',formset
print'3.Formset clean_data',formset。 clean_data
else:
formset = Formset()
返回render_to_response('template.html',localals())
虽然formset是有效的,它实际上包含数据,第3行打印一个空字典的列表,除非我实际上更改了字段中的初始值。
$ b $这对我来说似乎很奇怪,但我可能会做错事?任何帮助?
一个表单呈现一堆表单以及几个隐藏的输入字段,其中包含最多数量的表单等信息。因此,正确POST POST的表单始终包含数据。
而且,CharField 名称
内的初始Foo是原因那个表单有空字典。当表单的 empty_permitted
设置为True时,表单的所有项目等于其初始值,Django将将表单视为空,并将其clean_data设置为空字符串。 empty_permitted
默认为False,对于额外的表单,formset将设置为True。因此,在您点击提交w / o编辑值Foo后,表单实例被视为空,因此包装表单的表单获得了一个空的clean_data。
I 've been experiencing a weird problem, regarding django 1.4 and formsets: when the submitted data is unchanged, the cleaned_data field of the formset is empty, even if the formset itself passes the validation.
Here is an example:
forms.py:
class NameForm(forms.Form):
name = forms.CharField(required=False, initial='Foo')
views.py:
def welcome(request):
Formset = formset_factory(NameForm, extra=1)
if request.method == 'POST':
formset = Formset(request.POST)
print '1.Formset is valid?', formset.is_valid()
print '2.Formset', formset
print '3.Formset cleaned_data', formset.cleaned_data
else:
formset = Formset()
return render_to_response('template.html', locals())
Although formset is valid, and it actually contains data, line 3 prints a list of an empty dictionary, unless I 've actually changed the initial value in the field.
This seems weird to me, but I 'm probably doing something wrong? Any help?
A formset renders bunch of forms as well as several hidden input fields holding info such as max number of forms. Thus a correctly POSTed formset always contains data.
And, the initial 'Foo' inside CharField name
is the reason that formset got empty dictionary. When empty_permitted
of a form is set to True, and all items of the form equals to its initial value, Django will treat the form as empty and set its cleaned_data to be empty dict. The empty_permitted
defaults to False, formset will set it to True for extra forms. Thus after you clicked submit w/o editing the value 'Foo', the form instance was treated as empty, hence the formset wrapping the form got an empty cleaned_data.
这篇关于Django formset clean_data为空时提交表单不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!