[Django]-Django formset if TOTAL_FORMS has different number than actual number of forms

0πŸ‘

βœ…

It’s an old question and I am not sure if Django has changed much since. But the way I ended up doing it was to write a function to update formset data. The key here is to make a copy of the formset data (QueryDict) first. Here is the code:

def updateFormDataPrefixes(formset):
    """
    Update the data of the formset to fix the indices. This will assign
    indices to start from 0 to the length. To do this requires copying 
    the existing data and update the keys of the QueryDict. 
    """

    # Copy the current data first
    data = formset.data.copy()

    i = 0
    nums = []
    for form in formset.forms:
        num = form.prefix.split('-')[-1]
        nums.append(num)
        # Find the keys for this form
        matched_keys = [key for key in data if key.startswith(form.prefix)]
        for key in matched_keys:
            new_key = key.replace(num, '%d'%i)
            # If same key just move to the next form
            if new_key == key:
                break
            # Update the form key with the proper index
            data[new_key] = data[key]
            # Remove data with old key
            del data[key]
        # Update form data with the new key for this form
        form.data = data
        form.prefix = form.prefix.replace(num, '%d'%i)
        i += 1

    total_forms_key = formset.add_prefix(TOTAL_FORM_COUNT)
    data[total_forms_key] = len(formset.forms)
    formset.data = data
πŸ‘€maulik13

-1πŸ‘

Lol, It still old question, but real answer is β€œadd extra=0 attribute, because default extra definition is 3β€³

LinkFormSet = inlineformset_factory(
    ParentModel, 
    ChildModel,  
    fields = ('price', 'deadline',), 
    extra=0
)

More documentation is available here : https://docs.djangoproject.com/en/2.1/ref/forms/models/#django.forms.models.inlineformset_factory

πŸ‘€Oleg

Leave a comment