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

查看:16
本文介绍了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 请求的视图中创建并尝试验证它时:

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)

然后当表单集检查额外的表单时,它会看到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天全站免登陆