Open In App
Related Articles

error_messages – Django Form Field Validation

Improve Article
Save Article
Like Article

Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments.

The error_messages argument lets you specify manual error messages for attributes of the field. The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message:

>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean('')
Traceback (most recent call last):
ValidationError: ['This field is required.']

And here is a custom error message:

>>> name = forms.CharField(
               'required': 'Please enter your name'
>>> name.clean('')
Traceback (most recent call last):
ValidationError: ['Please enter your name']


field_name = models.Field(option = value)

Django Form Field Validation error_messages Explanation

Illustration of error_messages using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

Enter the following code into file of geeks app. We will be using CharField for experimenting for all field options.

from django import forms
class GeeksForm(forms.Form):
    geeks_field = forms.CharField(
                  error_messages = {
                 'required':"Please Enter your Name"

Add the geeks app to INSTALLED_APPS

# Application definition

Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in of geeks app,

from django.shortcuts import render
from .forms import GeeksForm
# Create your views here.
def home_view(request):
    context = {}
    form = GeeksForm(request.POST or None)
    context['form'] = form
    if request.POST:
        if form.is_valid():
            temp = form.cleaned_data.get("geeks_field")
    return render(request, "home.html", context)

Here we are importing that particular form from and creating an object of it in the view so that it can be rendered in a template.
Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.

<form method = "POST">
    {% csrf_token %}
    {{ form }}
    <input type = "submit" value = "Submit">

Finally, a URL to map to this view in

from django.urls import path
# importing views from
from .views import home_view
URLpatterns = [
    path('', home_view ),

Let’s run the server and check what has actually happened, Run

Python runserver

error_messages - Django Form Field Validation

Now let’s try to submit it empty and check if required error_message has been overridden.


Thus the field is displaying a custom error message for required attribute of Charfield.

More Built-in Form Validations

Field Options Description
required By default, each Field class assumes the value is required, so to make it not required you need to set required=False
label The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
label_suffix The label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widget The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_text The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods.
error_messages The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
validators The validators argument lets you provide a list of validation functions for this field.
localize The localize argument enables the localization of form data input, as well as the rendered output.
disabled. The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 15 Apr, 2020
Like Article
Save Article
Similar Reads
Complete Tutorials