Thameem Thameem - 1 year ago 62
Python Question

Django Formset Errors With Input Name

I want to get formset errors corresponding to its input name. Here I am using ajax to send the form data.

class Category(models.Model):
category = models.CharField(max_length=128)

class CategoryForm(forms.ModelForm):
class Meta:
field ="__all__"

CategoryFormset = modelformset_factory(Category, CategoryForm, , min_num=2, extra=0)

when i submit the form, i got the errors like this

python shell

[{'category': [u'This field is required.']}, {'category': [u'This field is required.']}]

But in my templates input name is different
. So is it possible to get errors something like this:
[{'form-0-category': [u'This field is required.']}, {'form-1-category': [u'This field is required.']}]
Somebody please help me.


<input id="id_form-0-category" maxlength="128" name="form-0-category" type="text"/>

<input id="id_form-1-category" maxlength="128" name="form-1-category" type="text" />

Answer Source

Django doesn't provide the list of errors in the format you want, but you can generate it yourself:

prefixed_errors = [{'%s-%s-%s' % (formset.prefix, index, k): v for k,v in errors.items()}
                   for (index, errors) in enumerate(formset.errors)]

This generates a list of dictionaries as in your question. I think you might want a single dictionary, which you could get with:

errors_dict = {'%s-%s-%s' % (prefix, index, k): v for (index, errors) in enumerate(formset_errors) for k,v in errors.items()}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download