Thameem
Thameem

Reputation: 3636

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.

models.py

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

forms.py

class CategoryForm(forms.ModelForm):
   class Meta:
     model=Category
     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

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

But in my templates input name is different form-0-category and form-1-category. 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.

templates

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

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

Upvotes: 2

Views: 384

Answers (1)

Alasdair
Alasdair

Reputation: 308869

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' % (formset.prefix, index, k): v for (index, errors) in enumerate(formset.errors) for k,v in errors.items()}

Upvotes: 2

Related Questions