Bob Stone
Bob Stone

Reputation: 100

How do I throw a custom error that specifies what field needs to be filled out

How do I specify what field needs to be filled out when giving an error in django. Right now the error is just "this field is required," but how do I change this field into the actual field like password, or username or something. So instead of the normal error: "This field is required" it should give: "Password is required or Email is required," based of the field.

Here is the code for the errors:

            {% if form.errors %}
                {% for field in form %}
                    {% for error in field.errors %}
                        <p class=" label label-danger">
                    <div style="text-align: center">
                     {{ error }}
                    </div>
                </p>
                    {% endfor %}
                {% endfor %}
                {% for error in form.non_field_errors %}
                    <div class="alert alert-danger">
                        <strong>{{ error|escape }}</strong>
                    </div>
                {% endfor %}
            {% endif %}

Upvotes: 0

Views: 48

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32284

You can override the required error message by passing error_messages to the field

class MyForm(forms.Form):
    some_field = forms.CharField(error_messages={'required': 'Some field is required'})

Upvotes: 2

Related Questions