Django Formset.is_valid() failing for extra forms

前端 未结 2 778
孤街浪徒
孤街浪徒 2020-12-30 04:20

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).

2条回答
  •  鱼传尺愫
    2020-12-30 04:33

    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.

    So for a form like this:

    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)
    

    we do this:

    pickme = forms.ChoiceField(choices=choices, initial=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.

提交回复
热议问题