Django Formset.is_valid()失败的额外的表单 [英] Django Formset.is_valid() failing for extra forms

查看:566
本文介绍了Django Formset.is_valid()失败的额外的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django应用程序应用程序中,我有一个从一个简单(非模型)形式创建的表单,其中extra = 1(允许javasript稍后添加更多表单)。

In my Django application application I have a formset that is created from a simple (not-model) form, with the extra=1 (to allow javasript to add more forms later on).

class SomeForm(forms.Form):
    #some fields with required=False
    length = forms.IntegerField(required=False)

    # An example of one of the fields with choices i have
    A = 0
    B = 1
    C = 2
    D = 3

    choices = ((A, 'Aah'), (B, 'Baa'), (C, 'Caa'), (D, 'Daa'))

    # This is a required choice field
    pickme = forms.ChoiceField(choices=choices)


SomeFormset = formset_factory(SomeForm, can_delete=True, extra=1)

现在,我创建并尝试在POST视图中验证POST请求:

Now, when I create and try to validate it in my view on the POST request:

my_formset = SomeFormset(request.POST, request.FILES)

if(my_formset.is_valid()):
    # FAIL

它总是失败上述检查,如果额外呈现的表单被提交为空。

it always fails the above check, if the extra rendered form is submitted empty.

如果我检查 form.changed_data 在最后一个空的额外的表单,我得到有选择的领域(如上面的 pickme )。
换句话说,当需要某些选择字段时,表单集不够明确,应该忽略空的提交表单。

If I check for form.changed_data on the last empty extra form, I get the fields that have choices on them (like the pickme above). In other words, the formset is not smart enough to figure out that the empty submitted form should be ignored, when some choice fields are required.

推荐答案

谢谢Carl,
你带领我发现我的问题的根源。

Thanks Carl, you led me to discover the root of my problem.

当创建一个带有选择字段的表单时,这是必需的,我们必须设置一个初始值,否则表单将考虑该字段更改

When creating a form with a choice field, which is required, we must set an initial value, otherwise the form will consider that field changed.

所以对于这样的形式:

class SomeForm(forms.Form):

    A = 0
    B = 1
    C = 2
    D = 3

   choices = ((A, 'Aah'), (B, 'Baa'), (C, 'Caa'), (D, 'Daa'))

    # This is a required choice field
    pickme = forms.ChoiceField(choices=choices)

我们这样做:

pickme = forms.ChoiceField(choices=choices, initial=A)

然后当一个formset chec ks是额外的形式,它会看到pickme的初始值为A,现在也是A,并且会考虑它不变。

Then when a formset checks the extra form it will see that pickme had an initial value of A, and it is A now as well, and will consider it unchanged.

这篇关于Django Formset.is_valid()失败的额外的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆