[Django]-Django Management Form is failing because 'form-TOTAL_FORMS' and 'form-INITIAL_FORMS' aren't correctly populated

5šŸ‘

āœ…

Update:

After looking through the example you provided there’s a snippet that reads like this in forms.py at the end of the add_fields() method:

# store the formset in the .nested property
form.nested = [
    TenantFormset(data = self.data,
                  instance = instance,
                  prefix = 'TENANTS_%s' % pk_value)
]

The data argument is causing problems because it’s initially empty and internally Django will determine whether or not a form is bound by a conditional that’s similar to this:

self.is_bound = data is not None

# Example
>>> my_data = {}
>>> my_data is not None
True

And as you can see an empty dictionary in Python isn’t None, so your TenantFormset is treated as a bound form even though it isn’t. You could fix it with something like the following:

# store the formset in the .nested property
form.nested = [
    TenantFormset(data = self.data if any(self.data) else None,
                  instance = instance,
                  prefix = 'TENANTS_%s' % pk_value)
]

Could you post the view and form code as well as the template code for your form?

My guess is that you’re not using the ā€˜management_form’ in your template (which adds the ā€œform-TOTAL_FORMSā€ and ā€œform-INITIAL_FORMSā€ fields that you’re missing), i.e.

<form method="post">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
        {{ form }}
        {% endfor %}
    </table>
</form>
šŸ‘¤Matt

Leave a comment