Django: How to add an extra form to a formset after it has been constructed?

后端 未结 4 1172
误落风尘
误落风尘 2021-02-01 21:44

This is roughly what I\'m trying to do:

def post(request):
    VehicleFormSet = formset_factory(StaffVehicleForm)
    if request.method == \'POST\':
        vehi         


        
4条回答
  •  名媛妹妹
    2021-02-01 22:33

    class RequiredFormSet(BaseFormSet):
        def add_form(self, **kwargs):
            # add the form
            tfc = self.total_form_count()
            self.forms.append(self._construct_form(tfc, **kwargs))
            self.forms[tfc].is_bound = False
    
            # make data mutable
            self.data = self.data.copy()
    
            # increase hidden form counts
            total_count_name = '%s-%s' % (self.management_form.prefix, TOTAL_FORM_COUNT)
            initial_count_name = '%s-%s' % (self.management_form.prefix, INITIAL_FORM_COUNT)
            self.data[total_count_name] = self.management_form.cleaned_data[TOTAL_FORM_COUNT] + 1
            self.data[initial_count_name] = self.management_form.cleaned_data[INITIAL_FORM_COUNT] + 1
    
        def add_fields(self, form, index):
            super(RequiredFormSet, self).add_fields(form, index)
            form.empty_permitted = False
    

    That will do it. Only took 7 hours to figure out. And I still don't know why I need .is_bound = False to make the initial values not screw up.

提交回复
热议问题