What are non field errors in django forms

In Django forms (including ModelForm), non_field_errors are errors that are not associated with any specific form field but are relevant to the form as a whole. These errors occur during form validation and represent issues that apply to the form's data globally rather than to individual fields.

non_field_errors are typically used when you need to validate data across multiple fields or when certain conditions must be met across the entire form. For example, you might want to ensure that the form data adheres to some business rules that involve multiple fields or perform checks that require the context of the entire form.

Example: Login form if username and password is incorrect then we raise ValidationError that Username or Password is incorrect. This is not related to any field. We have to say that login credentials are incorrect.

You can add non_field_errors to a form by raising a ValidationError with the NON_FIELD_ERRORS key. The NON_FIELD_ERRORS key is a special constant provided by Django to indicate non-field errors. Here's an example of how to add non_field_errors in a Django form:


forms.py:

from django import forms


class MyForm(forms.Form):

    field1 = forms.CharField()

    field2 = forms.IntegerField()

 

    def clean(self):

        cleaned_data = super().clean()

        field1_value = cleaned_data.get('field1')

        field2_value = cleaned_data.get('field2')

 

        if field1_value == 'foo' and field2_value == 42:

            raise forms.ValidationError(

                "You cannot have 'foo' for field1 and 42 for field2 at the same time.",

                code='invalid_combination',

            )

        return cleaned_data


In this example, we have a custom form MyForm with two fields, field1 and field2. In the clean() method, we check if field1 has the value 'foo' and field2 has the value 42 simultaneously. If this condition is met, we raise a ValidationError with the NON_FIELD_ERRORS key and a custom error message.

You can then access and display these non-field errors in the template as follows:

template.html:

<form method="post">

  {% csrf_token %}

  {{ form.as_p }}

  {% if form.non_field_errors %}

    <ul>

      {% for error in form.non_field_errors %}

        <li>{{ error }}</li>

      {% endfor %}

    </ul>

  {% endif %}

  <button type="submit">Submit</button>

</form>

In the template, we use form.non_field_errors to check if there are any non-field errors. If there are, we iterate over them using a loop and display each error message.

Using non_field_errors, you can provide additional information about the form validation issues that apply to the form as a whole and guide the user in providing valid data.

Comments

Popular posts from this blog

Implicit objects in Django template

Token Authentication in Django rest framework : Using Curl commands