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

£可爱£侵袭症+ 提交于 2019-12-03 21:18:33

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!