Daniil
Daniil

Reputation: 163

Why modelformset always returns error "this field is required"?

I try to render modelformset in a template manually and when I hit submit button it gives an error saying that "This field is required.". I create modelformset like this:

from django.forms import modelformset_factory

ImageFormset = modelformset_factory(PostImages, fields=('image',), extra=0, can_delete=True)
formset = ImageFormset(queryset=post.postimages_set.all())

And when I render modelformset like this, everything works:

{{ formset.management_form }}
{{ formset.as_p }}

But when I render it like this I get an error:

{{ formset.management_form }}
{% for f in formset %}
    <img src="/media/{{ f.image.value}}" style="max-width: 400px;" alt="">
    {{ f.image }}
    {{ f.DELETE }}
{% endfor %}

Upvotes: 1

Views: 232

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

The model formset adds a hidden field with the model instances primary key to the form to be able to identify which object is which. When you render the form manually you are not rendering it, causing the form to give you an error because it does not find it.

Simply as a best practice when rendering forms manually, just loop over a forms hidden fields and render them:

{{ formset.management_form }}
{% for f in formset %}
    {% for field in f.hidden_fields %}
        {{ field }}
    {% endfor %}
    <img src="/media/{{ f.image.value}}" style="max-width: 400px;" alt="">
    {{ f.image }}
    {{ f.DELETE }}
{% endfor %}

Upvotes: 2

Related Questions