dreamzboy
dreamzboy

Reputation: 841

Append to Django Form Validation Error?

I'm using custom validation error in Django 1.6 and it's working great; however, I can only display one error at a time. How do I go about displaying all errors if the condition in the "if" statements failed?

forms.py

class BaseNameFormSet (BaseFormSet):
...
...
...
if (firstname in firstnames) or (lastname in lastnames):
    raise forms.ValidationError ('First or last name must be unique')
if (firstname == '') or (lastname == ''):
    raise forms.ValidationError ('Both first and last name must be filled out')

addname.html

...
...
...
    {% if formset.non_form_errors %}
        <b>Please correct the error below:</b>
        <ul>
            {% for error in formset.non_form_errors %}
            <li><p style="color: red;"> {{ error }} </p></li>
        {% endfor %}
        </ul>

Upvotes: 2

Views: 1475

Answers (2)

Alasdair
Alasdair

Reputation: 308909

If you are able to upgrade to Django 1.7, you can raise multiple errors by passing a list to the ValidationError constructor.

errors = []
if (firstname in firstnames) or (lastname in lastnames):
    errors.append('First or last name must be unique')
if (firstname == '') or (lastname == ''):
    errors.append('Both first and last name must be filled out')
if errors:
    raise ValidationError(errors)

Note that you shouldn't usually have to do checks like if firstname == '', just make firstname a required field. You might find this question about making a forms in a formset required to be useful.

Upvotes: 1

Alex Lord Mordor
Alex Lord Mordor

Reputation: 3050

You can declare a variable that is filled with the errors, then display it once at the end.

class BaseNameFormSet (BaseFormSet):
    ...
    ...
    ...

    if (firstname in firstnames) or (lastname in lastnames):
         error_msg='First or last name must be unique'
    if (firstname == '') or (lastname == ''):
        error_msg+='<br>Both first and last name must be filled out'
    if error_msg:
        raise forms.ValidationError(error_msg)

Upvotes: 1

Related Questions