Django forms custom error

I can see how to add an error message to a field when using forms, but what about model form? This is my test model: class Author(models.Model): first_name = models.CharField(max_length=125) ...

I can see how to add an error message to a field when using forms, but what about model form?

This is my test model:

class Author(models.Model):
    first_name = models.CharField(max_length=125)
    last_name = models.CharField(max_length=125)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

My model form:

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

The error message on the fields: first_name and last_name is:

This field is required

How do I change that in a model form?

Milo's user avatar

Milo

3,2979 gold badges28 silver badges43 bronze badges

asked Aug 9, 2010 at 0:44

iJK's user avatar

For simple cases, you can specify custom error messages

class AuthorForm(forms.ModelForm):
    first_name = forms.CharField(error_messages={'required': 'Please let us know what to call you!'})
    class Meta:
        model = Author

davelupt's user avatar

davelupt

1,7754 gold badges20 silver badges32 bronze badges

answered Aug 9, 2010 at 3:29

chefsmart's user avatar

chefsmartchefsmart

6,7839 gold badges42 silver badges47 bronze badges

4

New in Django 1.6:

ModelForm accepts several new Meta options.

  • Fields included in the localized_fields list will be localized (by setting localize on the form field).
  • The labels, help_texts and error_messages options may be used to customize the default fields, see Overriding the default fields for details.

From that:

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }

Related: Django’s ModelForm — where is the list of Meta options?

Community's user avatar

answered Feb 13, 2014 at 18:44

doctaphred's user avatar

doctaphreddoctaphred

2,4341 gold badge23 silver badges26 bronze badges

6

Another easy way of doing this is just override it in init.

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

    def __init__(self, *args, **kwargs):
        super(AuthorForm, self).__init__(*args, **kwargs)

        # add custom error messages
        self.fields['name'].error_messages.update({
            'required': 'Please let us know what to call you!',
        })

slajma's user avatar

slajma

1,43914 silver badges16 bronze badges

answered Mar 27, 2013 at 3:11

jamesmfriedman's user avatar

2

I have wondered about this many times as well. That’s why I finally wrote a small extension to the ModelForm class, which allows me to set arbitrary field attributes — including the error messages — via the Meta class. The code and explanation can be found here: http://blog.brendel.com/2012/01/django-modelforms-setting-any-field.html

You will be able to do things like this:

class AuthorForm(ExtendedMetaModelForm):
    class Meta:
        model = Author
        field_args = {
            "first_name" : {
                "error_messages" : {
                    "required" : "Please let us know what to call you!"
                }
            }
        }

I think that’s what you are looking for, right?

answered Jan 23, 2012 at 19:11

jbrendel's user avatar

jbrendeljbrendel

2,3503 gold badges17 silver badges17 bronze badges

2

the easyest way is to override the clean method:

class AuthorForm(forms.ModelForm):
   class Meta:
      model = Author
   def clean(self):
      if self.cleaned_data.get('name')=="":
         raise forms.ValidationError('No name!')
      return self.cleaned_data

answered Aug 9, 2010 at 1:11

Mermoz's user avatar

MermozMermoz

14.5k17 gold badges59 silver badges84 bronze badges

I have a cleaner solution, based on jamesmfriedman’s answer.
This solution is even more DRY, especially if you have lots of fields.

custom_errors = {
    'required': 'Your custom error message'
}

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author

    def __init__(self, *args, **kwargs):
        super(AuthorForm, self).__init__(*args, **kwargs)

        for field in self.fields:
            self.fields[field].error_messages = custom_errors

answered Feb 17, 2015 at 19:54

Vingtoft's user avatar

VingtoftVingtoft

12.7k22 gold badges80 silver badges127 bronze badges

You can easily check and put custom error message by overriding clean()method and using self.add_error(field, message):

def clean(self):
    super(PromotionForm, self).clean()
    error_message = ''
    field = ''
    # reusable check
    if self.cleaned_data['reusable'] == 0:
        error_message = 'reusable should not be zero'
        field = 'reusable'
        self.add_error(field, error_message)
        raise ValidationError(error_message)

    return self.cleaned_data

answered May 31, 2017 at 9:56

Moe Far's user avatar

Moe FarMoe Far

2,7322 gold badges21 silver badges41 bronze badges

Form and field validation¶

Form validation happens when the data is cleaned. If you want to customize
this process, there are various places to make changes, each one serving a
different purpose. Three types of cleaning methods are run during form
processing. These are normally executed when you call the is_valid()
method on a form. There are other things that can also trigger cleaning and
validation (accessing the errors attribute or calling full_clean()
directly), but normally they won’t be needed.

In general, any cleaning method can raise ValidationError if there is a
problem with the data it is processing, passing the relevant information to
the ValidationError constructor. See below
for the best practice in raising ValidationError. If no ValidationError
is raised, the method should return the cleaned (normalized) data as a Python
object.

Most validation can be done using validators — helpers that can be reused.
Validators are functions (or callables) that take a single argument and raise
ValidationError on invalid input. Validators are run after the field’s
to_python and validate methods have been called.

Validation of a form is split into several steps, which can be customized or
overridden:

  • The to_python() method on a Field is the first step in every
    validation. It coerces the value to a correct datatype and raises
    ValidationError if that is not possible. This method accepts the raw
    value from the widget and returns the converted value. For example, a
    FloatField will turn the data into a Python float or raise a
    ValidationError.

  • The validate() method on a Field handles field-specific validation
    that is not suitable for a validator. It takes a value that has been
    coerced to a correct datatype and raises ValidationError on any error.
    This method does not return anything and shouldn’t alter the value. You
    should override it to handle validation logic that you can’t or don’t
    want to put in a validator.

  • The run_validators() method on a Field runs all of the field’s
    validators and aggregates all the errors into a single
    ValidationError. You shouldn’t need to override this method.

  • The clean() method on a Field subclass is responsible for running
    to_python(), validate(), and run_validators() in the correct
    order and propagating their errors. If, at any time, any of the methods
    raise ValidationError, the validation stops and that error is raised.
    This method returns the clean data, which is then inserted into the
    cleaned_data dictionary of the form.

  • The clean_<fieldname>() method is called on a form subclass – where
    <fieldname> is replaced with the name of the form field attribute.
    This method does any cleaning that is specific to that particular
    attribute, unrelated to the type of field that it is. This method is not
    passed any parameters. You will need to look up the value of the field
    in self.cleaned_data and remember that it will be a Python object
    at this point, not the original string submitted in the form (it will be
    in cleaned_data because the general field clean() method, above,
    has already cleaned the data once).

    For example, if you wanted to validate that the contents of a
    CharField called serialnumber was unique,
    clean_serialnumber() would be the right place to do this. You don’t
    need a specific field (it’s a CharField), but you want a
    formfield-specific piece of validation and, possibly, cleaning/normalizing
    the data.

    The return value of this method replaces the existing value in
    cleaned_data, so it must be the field’s value from cleaned_data (even
    if this method didn’t change it) or a new cleaned value.

  • The form subclass’s clean() method can perform validation that requires
    access to multiple form fields. This is where you might put in checks such as
    “if field A is supplied, field B must contain a valid email address”.
    This method can return a completely different dictionary if it wishes, which
    will be used as the cleaned_data.

    Since the field validation methods have been run by the time clean() is
    called, you also have access to the form’s errors attribute which
    contains all the errors raised by cleaning of individual fields.

    Note that any errors raised by your Form.clean() override will not
    be associated with any field in particular. They go into a special
    “field” (called __all__), which you can access via the
    non_field_errors() method if you need to. If you
    want to attach errors to a specific field in the form, you need to call
    add_error().

    Also note that there are special considerations when overriding
    the clean() method of a ModelForm subclass. (see the
    ModelForm documentation for more information)

These methods are run in the order given above, one field at a time. That is,
for each field in the form (in the order they are declared in the form
definition), the Field.clean() method (or its override) is run, then
clean_<fieldname>(). Finally, once those two methods are run for every
field, the Form.clean() method, or its override, is executed whether
or not the previous methods have raised errors.

Examples of each of these methods are provided below.

As mentioned, any of these methods can raise a ValidationError. For any
field, if the Field.clean() method raises a ValidationError, any
field-specific cleaning method is not called. However, the cleaning methods
for all remaining fields are still executed.

Raising ValidationError

In order to make error messages flexible and easy to override, consider the
following guidelines:

  • Provide a descriptive error code to the constructor:

    # Good
    ValidationError(_('Invalid value'), code='invalid')
    
    # Bad
    ValidationError(_('Invalid value'))
    
  • Don’t coerce variables into the message; use placeholders and the params
    argument of the constructor:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(_('Invalid value: %s') % value)
    
  • Use mapping keys instead of positional formatting. This enables putting
    the variables in any order or omitting them altogether when rewriting the
    message:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(
        _('Invalid value: %s'),
        params=('42',),
    )
    
  • Wrap the message with gettext to enable translation:

    # Good
    ValidationError(_('Invalid value'))
    
    # Bad
    ValidationError('Invalid value')
    

Putting it all together:

raise ValidationError(
    _('Invalid value: %(value)s'),
    code='invalid',
    params={'value': '42'},
)

Following these guidelines is particularly necessary if you write reusable
forms, form fields, and model fields.

While not recommended, if you are at the end of the validation chain
(i.e. your form clean() method) and you know you will never need
to override your error message you can still opt for the less verbose:

ValidationError(_('Invalid value: %s') % value)

The Form.errors.as_data() and
Form.errors.as_json() methods
greatly benefit from fully featured ValidationErrors (with a code name
and a params dictionary).

Raising multiple errors¶

If you detect multiple errors during a cleaning method and wish to signal all
of them to the form submitter, it is possible to pass a list of errors to the
ValidationError constructor.

As above, it is recommended to pass a list of ValidationError instances
with codes and params but a list of strings will also work:

# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])

Using validation in practice¶

The previous sections explained how validation works in general for forms.
Since it can sometimes be easier to put things into place by seeing each
feature in use, here are a series of small examples that use each of the
previous features.

Using validators¶

Django’s form (and model) fields support use of utility functions and classes
known as validators. A validator is a callable object or function that takes a
value and returns nothing if the value is valid or raises a
ValidationError if not. These can be passed to a
field’s constructor, via the field’s validators argument, or defined on the
Field class itself with the default_validators
attribute.

Validators can be used to validate values inside the field, let’s have a look
at Django’s SlugField:

from django.core import validators
from django.forms import CharField

class SlugField(CharField):
    default_validators = [validators.validate_slug]

As you can see, SlugField is a CharField with a customized validator
that validates that submitted text obeys to some character rules. This can also
be done on field definition so:

is equivalent to:

slug = forms.CharField(validators=[validators.validate_slug])

Common cases such as validating against an email or a regular expression can be
handled using existing validator classes available in Django. For example,
validators.validate_slug is an instance of
a RegexValidator constructed with the first
argument being the pattern: ^[-a-zA-Z0-9_]+$. See the section on
writing validators to see a list of what is already
available and for an example of how to write a validator.

Form field default cleaning¶

Let’s first create a custom form field that validates its input is a string
containing comma-separated email addresses. The full class looks like this:

from django import forms
from django.core.validators import validate_email

class MultiEmailField(forms.Field):
    def to_python(self, value):
        """Normalize data to a list of strings."""
        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')

    def validate(self, value):
        """Check if value consists only of valid emails."""
        # Use the parent's handling of required fields, etc.
        super().validate(value)
        for email in value:
            validate_email(email)

Every form that uses this field will have these methods run before anything
else can be done with the field’s data. This is cleaning that is specific to
this type of field, regardless of how it is subsequently used.

Let’s create a ContactForm to demonstrate how you’d use this field:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    recipients = MultiEmailField()
    cc_myself = forms.BooleanField(required=False)

Use MultiEmailField like any other form field. When the is_valid()
method is called on the form, the MultiEmailField.clean() method will be
run as part of the cleaning process and it will, in turn, call the custom
to_python() and validate() methods.

Cleaning a specific field attribute¶

Continuing on from the previous example, suppose that in our ContactForm,
we want to make sure that the recipients field always contains the address
"fred@example.com". This is validation that is specific to our form, so we
don’t want to put it into the general MultiEmailField class. Instead, we
write a cleaning method that operates on the recipients field, like so:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise ValidationError("You have forgotten about Fred!")

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data

Cleaning and validating fields that depend on each other¶

Suppose we add another requirement to our contact form: if the cc_myself
field is True, the subject must contain the word "help". We are
performing validation on more than one field at a time, so the form’s
clean() method is a good spot to do this. Notice that we are
talking about the clean() method on the form here, whereas earlier we were
writing a clean() method on a field. It’s important to keep the field and
form difference clear when working out where to validate things. Fields are
single data points, forms are a collection of fields.

By the time the form’s clean() method is called, all the individual field
clean methods will have been run (the previous two sections), so
self.cleaned_data will be populated with any data that has survived so
far. So you also need to remember to allow for the fact that the fields you
are wanting to validate might not have survived the initial individual field
checks.

There are two ways to report any errors from this step. Probably the most
common method is to display the error at the top of the form. To create such
an error, you can raise a ValidationError from the clean() method. For
example:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

In this code, if the validation error is raised, the form will display an
error message at the top of the form (normally) describing the problem. Such
errors are non-field errors, which are displayed in the template with
{{ form.non_field_errors }}.

The call to super().clean() in the example code ensures that any validation
logic in parent classes is maintained. If your form inherits another that
doesn’t return a cleaned_data dictionary in its clean() method (doing
so is optional), then don’t assign cleaned_data to the result of the
super() call and use self.cleaned_data instead:

def clean(self):
    super().clean()
    cc_myself = self.cleaned_data.get("cc_myself")
    ...

The second approach for reporting validation errors might involve assigning the
error message to one of the fields. In this case, let’s assign an error message
to both the “subject” and “cc_myself” rows in the form display. Be careful when
doing this in practice, since it can lead to confusing form output. We’re
showing what is possible here and leaving it up to you and your designers to
work out what works effectively in your particular situation. Our new code
(replacing the previous sample) looks like this:

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject and "help" not in subject:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)

The second argument of add_error() can be a string, or preferably an
instance of ValidationError. See Raising ValidationError for more
details. Note that add_error() automatically removes the field from
cleaned_data.

14.03.2012

Думаю, вы хотите, чтобы ваши сообщения об ошибках в заполняемых формах были на том же языке, что и сам сайт. Один из простых способов — это добавить следующий код в соответствующий forms.py. Затем формы надо будет наследовать не от forms.Form, а от MyForm (обратите внимание, ExampleForm, в примере ниже, наследуется от него).

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for k, field in self.fields.items():
            if 'required' in field.error_messages:
                field.error_messages['required'] = u'Это поле обязательно!'

class ExampleForm(MyForm):
    title = forms.CharField(max_length=100, required=True, label=u'Название')

Полный список error_messages для различных типов полей можно увидеть, если просмотреть этот раздел: https://docs.djangoproject.com/en/1.3/ref/forms/fields/#built-in-field-classes

Вот что есть на данный момент:

required — показывается, если данное поле обязательно;
max_length — если превышено максимальное количество символов в символьном поле / в случае с файлами — длина имени файла;
min_length — если символов меньше, чем должно быть, в символьном поле;
invalid_choice — если выбран невозможный choice;
invalid — при неправильном email’е и прочем неправильном вводе данных;
max_value — если превышено числовое значение;
min_value — если значение меньше минимального числового ограничения;
max_digits — если превышено количество цифр в числе;
max_decimal_places — если превышено количество цифр после запятой;
max_whole_digits — если превышено количество цифр до запятой;
missing — если файл не найден;
empty — если файл пустой;
invalid_image — если изображение повреждено;
invalid_list  — если неправильный список choice’ов;
invalid_link — для URLField — вызывается, если данного url не существует.

Основано на примере с http://stackoverflow.com/questions/1481771/django-override-default-form-error-messages

django

In this post we’ll learn to create user-defined functions, displaying validation errors in the template for Django Form Validations.

Table Of Contents

  • Introduction
  • Creating Form
  • Rendering Form
  • Saving Form
  • Form Validation User-Defined Functions
  • Conclusion

Introduction

The forms are a Django Module which deals with all form-related functions from binding POST data to form, Validating form and rendering HTML field in the template.
We’ll be using below models.py file as an example to demonstrate form validations.

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class AuthUserProfile(models.Model):
    user_profile_id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='auth_user_profile')
    dob =  models.DateField(blank=True, null=True)
    is_deleted = models.PositiveSmallIntegerField(default=0)
    created_at = models.DateTimeField(auto_now=datetime.now(), null=True)
    updated_at = models.DateTimeField(auto_now=datetime.now(), null=True)

    class Meta():
        db_table = 'auth_user_profile'
        verbose_name = 'User Profile'
        verbose_name_plural = 'User Profiles'

    def __str__(self):
        return self.user

Create a form which has these fields (first_name, last_name, username, password, email) from User models and field (dob) in AuthUserProfile Model and also will add custom field and non-field level validation.

Creating Form

In forms.py file import forms from Django. Inherit forms.Form to UserForm and add attributes to the field.

from django import forms
from datetime import datetime
from django.contrib.auth.models import User

class UserForm(forms.Form):
    first_name = forms.CharField(label="First Name*",widget=forms.TextInput(attrs={'required':True,'class':"form-control"}))
    last_name = forms.CharField(label="Last Name*",widget=forms.TextInput(attrs={'required':True,'class':"form-control"}))
    username = forms.CharField(label="User Name*",widget=forms.TextInput(attrs={'required':True,'class':"form-control"}))
    email = forms.CharField(label="Email",widget=forms.TextInput(attrs={'type':'email','required':False,'class':"form-control"}))
    date_of_birth = forms.CharField(label="Date of Birth",widget=forms.TextInput(attrs={'type':'date','required':True,'class':"form-control"}))
    password = forms.CharField(label="Password*",widget=forms.TextInput(attrs={'required':True,'class':"form-control", 'type' : "password"}))
    confirm_password = forms.CharField(label="Confirm Password*",widget=forms.TextInput(attrs={'required':True,'class':"form-control", 'type' : "password"}))
    
    def clean(self):
        # user age must be above 18 to register
        if self.cleaned_data.get('date_of_birth'):
            dob = datetime.strptime(self.cleaned_data.get('date_of_birth'),"%Y-%m-%d")
            now = datetime.now()
            diff = now.year-dob.year

            if diff < 18: msg="User must be atleast 18 years old" self.add_error(None, msg) #check if user name is unique username_count = User.objects.filter(username=self.cleaned_data.get('username')).count() if username_count>0:
            msg="Username '{}' has already been used.".format(self.cleaned_data.get('username'))
            self.add_error(None, msg)
        
    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if confirm_password!=password:
            msg = "Password and Confirm Passwords must match."
            self.add_error('confirm_password', msg)

You may notice clean() and clean_confirm_password() methods in UserForm the form they are validation methods.
The clean() the method is form level validation this can also be used to perform field-level validation.

And the clean_confirm_password() is a field-level validation for confirm_password the field it checks if confirm_password!=password then adds error to a then particular field.

Rendering Form

Rendering of forms is an easy part we must pass the form object as an argument to render function.

In views.py create a function user_profile_create which will display rendered form.

from django.contrib.auth.models import User
from users.models import AuthUserProfile
from forms.forms import UserForm
from django.contrib.auth.hashers import make_password
from django.contrib import messages

def user_profile_create(request):
    form = UserForm()
    template="forms/user_profile_create_form.html"
    return render(request,template,{"form":form})

form = UserForm() creates form object of UserForm and is passed as an argument to the render() function.

In urls.py file add routes to view.

urlpatterns = [
    path('user/profile/create', views.user_profile_create, name='user-profile-create'),
]

Create an HTML file in your apps template folder naming user_profile_create_form.html.

<!DOCTYPE html>
<html lang="en">            
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Django Form Validation</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <style>
            .error{
                color:red;
            }
        </style>
    </head>            
    <body>
        <div class="container">
        
            {% if messages %}
                {% for message in messages %}
                    {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}
                    <div class="alert alert-success"
                    role="alert">
                        <div id="primary-notification-div">
                            {{ message }}
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
                
            <h1>User Profile</h1>
            <form action="{% url 'forms:user-profile-save' %}" method="post">
                {% csrf_token %}
    
                {% if form.errors %}
                    {% for error in form.non_field_errors %}
                        <div class="alert alert-danger">
                            <strong>{{ error|escape }}</strong>
                        </div>
                    {% endfor %}
    
                {% endif %}
    
    
                <div class="row">
                    <div class="col-md-3">
                        {{form.first_name.label}}
                        {{form.first_name}}
    
                        {% if form.errors.first_name %}
                            <label for="" class="error">{{form.errors.first_name|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.last_name.label}}
                        {{form.last_name}}
                        {% if form.errors.last_name %}
                            <label for="" class="error">{{form.errors.last_name|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.username.label}}
                        {{form.username}}
                        {% if form.errors.username %}
                            <label for="" class="error">{{form.errors.username|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.email.label}}
                        {{form.email}}
                        {% if form.errors.email %}
                            <label for="" class="error">{{form.errors.email|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.date_of_birth.label}}
                        {{form.date_of_birth}}
                        {% if form.errors.date_of_birth %}
                            <label for="" class="error">{{form.errors.date_of_birth|striptags}}</label>
                        {% endif %}
                    </div>
                </div>
    
                <div class="row" style="margin-top: 25px;">
                    <div class="col-md-3">
                        {{form.password.label}}
                        {{form.password}}
                        {% if form.errors.password %}
                            <label for="" class="error">{{form.errors.password|striptags}}</label>
                        {% endif %}
                    </div>
                </div>
    
                <div class="row" style="margin-top: 25px;">
    
                    <div class="col-md-3">
                        {{form.confirm_password.label}}
                        {{form.confirm_password}}
                        {% if form.errors.confirm_password %}
                        <label for="" class="error">{{form.errors.confirm_password|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-12" style="margin-top: 25px;">
                        <input type="submit" class="btn btn-sm btn-primary" value="submit">
                    </div>
                </div>
            </form>
        </div>
    </body>                
</html>

This is how our form will look when we go to route user/profile/create.

User Profile Form

  • The message displays success message once messages.add_message(request, messages.SUCCESS, ".....") is called it is just like the flash message.
  • The form.errors is called on validation has failed.
  • The form.non_field_errors display errors on top of form this errors are not associated to a particular field.
  • The form.errors. displays the error of the particular field.

This is how errors are displayed in the form.

User Profile Form Displaying Validation Errors

Saving Form

In urls.py file add routes to save the form.

urlpatterns = [
    path('user/profile/save', views.user_profile_create, name='user-profile-save'),
]

In views.py file add function user_profile_save() to save form data.

def user_profile_save(request):

    form = UserForm(request.POST)

    if form.is_valid():

        query = {
            "first_name" : form.cleaned_data.get('first_name'),
            "last_name" : form.cleaned_data.get('last_name'),
            "username" : form.cleaned_data.get('username'),
            "password" : make_password(form.cleaned_data.get('password')),
            "email" : form.cleaned_data.get('email'),
            "is_superuser" : 0,
            "is_staff" : 1,
            "is_active" : 1,
        }

        user = User.objects.create(**query)
        
        query={
            "user_id" : user.id,
            "dob" : form.cleaned_data.get('dob'),
        }
        
        AuthUserProfile.objects.create(**query)
        
        messages.add_message(request, messages.SUCCESS, "User Profile created successfully.")
        
        return HttpResponseRedirect(reverse('forms:user-profile-create'))
    
    template="forms/user_profile_create_form.html"
    
    return render(request,template,{"form":form})

The request.POST is passed to UserForm(request.POST) this binds the submitted data to Form Class.
The form.is_valid() returns a Boolean value if True then the form is clean and if False then there may be validation error.
To view validation errors after .is_valid() method we can print form.errors to view validation errors.

Calling form.cleaned_data.get('') gives use of the sanitized value to that field. Inside .is_valid() we have called model methods to save form data.

Showing success message on successfully validating form and saving its contents into the database

Form Validation User-Defined functions

To defined a custom validation function in Form Class name function with prefix clean followed by underscore and field name which must be validated.

Example

def clean_first_name(self):
    pass #this validates field first_name

def clean_username(self):
    pass #this validates field username

If the value of the field is not as expected that you can raise validation error or add error by mentioning field name self.add_error('field_name', "Error Message").
If you want to raise non-field error than set the first argument of add_error() method None followed by the message you want to be displayed.

self.add_error(None, msg) #this creates a non-field error

Conclusion

We have come to the end of our post on Django Form Validation.
If you have any doubts or suggestions please mention in the comments section and we’ll reach you soon and we would also love to hear requests and your recommendations for new tutorials/posts.

Related Posts

  • Python Django Forms | Creating, Rendering, Validating and Saving Forms
  • Django – Multiple Files Validation and Uploads

Summary

Review Date

2020-06-15

Reviewed Item

Django Forms | Custom Form Validations

Author Rating

51star1star1star1star1star

Software Name

Django Web Framework

Software Name

Windows Os, Mac Os, Ubuntu Os

Software Category

Web Development

Валидация форм и полей¶

Валидация формы происходит при очистке данных. Если вы хотите настроить этот процесс, есть различные места для внесения изменений, каждое из которых служит для разных целей. В процессе обработки формы выполняются три типа методов очистки. Обычно они выполняются, когда вы вызываете метод is_valid() на форме. Есть и другие вещи, которые также могут вызвать очистку и проверку (обращение к атрибуту errors или прямой вызов full_clean()), но обычно они не нужны.

В общем, любой метод очистки может поднять ValidationError, если есть проблема с данными, которые он обрабатывает, передавая соответствующую информацию конструктору ValidationError. See below для лучшей практики поднятия ValidationError. Если не поднимается ValidationError, метод должен вернуть очищенные (нормализованные) данные в виде объекта Python.

Большинство валидаций можно выполнить с помощью validators — помощников, которые можно использовать повторно. Валидаторы — это функции (или callables), которые принимают один аргумент и вызывают ValidationError при недопустимом вводе. Валидаторы запускаются после вызова методов to_python и validate поля.

Валидация формы разбита на несколько этапов, которые можно настроить или отменить:

  • Метод to_python() на Field является первым шагом в каждой валидации. Он преобразует значение к правильному типу данных и выдает сообщение ValidationError, если это невозможно. Этот метод принимает необработанное значение от виджета и возвращает преобразованное значение. Например, FloatField превратит данные в Python float или выдаст ValidationError.

  • Метод validate() на Field обрабатывает специфическую для поля валидацию, которая не подходит для валидатора. Он принимает значение, которое было приведено к правильному типу данных, и при любой ошибке выдает сообщение ValidationError. Этот метод ничего не возвращает и не должен изменять значение. Вы должны переопределить его для обработки логики валидации, которую вы не можете или не хотите поместить в валидатор.

  • Метод run_validators() на поле Field запускает все валидаторы поля и объединяет все ошибки в один ValidationError. Вам не нужно переопределять этот метод.

  • Метод clean() в подклассе Field отвечает за выполнение to_python(), validate() и run_validators() в правильном порядке и распространение их ошибок. Если в любой момент времени какой-либо из методов вызывает ошибку ValidationError, валидация останавливается, и эта ошибка выдается. Этот метод возвращает чистые данные, которые затем вставляются в словарь cleaned_data формы.

  • Метод clean_<fieldname>() вызывается на подклассе формы – где <fieldname> заменяется на имя атрибута поля формы. Этот метод выполняет любую очистку, специфичную для данного атрибута, не связанную с типом поля, которым он является. Этому методу не передаются никакие параметры. Вам нужно будет найти значение поля в self.cleaned_data и помнить, что в этот момент это будет объект Python, а не исходная строка, представленная в форме (она будет в cleaned_data, потому что метод general field clean(), описанный выше, уже однажды очистил данные).

    Например, если вы хотите проверить, что содержимое CharField под названием serialnumber является уникальным, clean_serialnumber() будет подходящим местом для этого. Вам не нужно конкретное поле (это CharField), но вам нужен специфический для поля формы фрагмент проверки и, возможно, очистки/нормализации данных.

    Возвращаемое значение этого метода заменяет существующее значение в cleaned_data, поэтому это должно быть значение поля из cleaned_data (даже если этот метод не изменил его) или новое очищенное значение.

  • Метод clean() подкласса формы может выполнять валидацию, требующую доступа к нескольким полям формы. Сюда можно отнести такие проверки, как «если поле A предоставлено, то поле B должно содержать действительный адрес электронной почты». При желании этот метод может вернуть совершенно другой словарь, который будет использован в качестве cleaned_data.

    Поскольку методы валидации полей были запущены к моменту вызова clean(), у вас также есть доступ к атрибуту errors формы, который содержит все ошибки, возникшие при очистке отдельных полей.

    Обратите внимание, что любые ошибки, возникающие при переопределении Form.clean(), не будут связаны с каким-либо конкретным полем. Они попадают в специальное «поле» (называемое __all__), к которому вы можете получить доступ через метод non_field_errors(), если вам это необходимо. Если вы хотите прикрепить ошибки к определенному полю формы, вам нужно вызвать add_error().

    Также обратите внимание, что существуют особые соображения при переопределении метода clean() подкласса ModelForm. (см. ModelForm documentation для получения дополнительной информации)

Эти методы выполняются в указанном выше порядке, по одному полю за раз. То есть, для каждого поля формы (в порядке их объявления в определении формы) выполняется метод Field.clean() (или его переопределение), затем clean_<fieldname>(). Наконец, когда эти два метода выполнены для каждого поля, выполняется метод Form.clean(), или его переопределение, независимо от того, вызвали ли предыдущие методы ошибки.

Примеры каждого из этих методов приведены ниже.

Как уже упоминалось, любой из этих методов может вызвать ошибку ValidationError. Для любого поля, если метод Field.clean() вызывает ValidationError, любой метод очистки, специфичный для данного поля, не вызывается. Однако методы очистки для всех оставшихся полей все равно выполняются.

Поднятие ValidationError

Чтобы сделать сообщения об ошибках гибкими и легко переопределяемыми, примите во внимание следующие рекомендации:

  • Предоставить описательную ошибку code конструктору:

    # Good
    ValidationError(_('Invalid value'), code='invalid')
    
    # Bad
    ValidationError(_('Invalid value'))
    
  • Не вставляйте переменные в сообщение; используйте заполнители и аргумент params конструктора:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(_('Invalid value: %s') % value)
    
  • Используйте ключи отображения вместо позиционного форматирования. Это позволяет располагать переменные в любом порядке или вообще их не использовать при переписывании сообщения:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(
        _('Invalid value: %s'),
        params=('42',),
    )
    
  • Оберните сообщение символом gettext, чтобы включить перевод:

    # Good
    ValidationError(_('Invalid value'))
    
    # Bad
    ValidationError('Invalid value')
    

Собираем все вместе:

raise ValidationError(
    _('Invalid value: %(value)s'),
    code='invalid',
    params={'value': '42'},
)

Следование этим рекомендациям особенно необходимо, если вы пишете многократно используемые формы, поля форм и поля моделей.

Хотя это и не рекомендуется, если вы находитесь в конце цепочки валидации (т.е. ваша форма clean() метод) и вы знаете, что вам никогда не понадобится переопределять сообщение об ошибке, вы можете выбрать менее многословный вариант:

ValidationError(_('Invalid value: %s') % value)

Методы Form.errors.as_data() и Form.errors.as_json() значительно выигрывают от полнофункциональных ValidationErrors (с code именем и params словарем).

Возникновение множества ошибок¶

Если вы обнаружили несколько ошибок во время работы метода очистки и хотите сигнализировать обо всех из них отправителю формы, можно передать список ошибок конструктору ValidationError.

Как и выше, рекомендуется передавать список экземпляров ValidationError с codes и params, но подойдет и список строк:

# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])

Использование валидации на практике¶

В предыдущих разделах объяснялось, как работает валидация в целом для форм. Поскольку иногда бывает проще понять, как работает каждая функция, здесь приведена серия небольших примеров, в которых используется каждая из предыдущих функций.

Использование валидаторов¶

Поля формы (и модели) Django поддерживают использование полезных функций и классов, известных как валидаторы. Валидатор — это вызываемый объект или функция, которая принимает значение и не возвращает ничего, если значение действительно, или выдает ошибку ValidationError, если нет. Они могут быть переданы в конструктор поля через аргумент validators или определены в самом классе Field с помощью атрибута default_validators.

Валидаторы могут использоваться для проверки значений внутри поля, давайте посмотрим на Django’s SlugField:

from django.core import validators
from django.forms import CharField

class SlugField(CharField):
    default_validators = [validators.validate_slug]

Как вы можете видеть, SlugField — это CharField с настроенным валидатором, который проверяет, что отправленный текст соответствует некоторым правилам символов. Это также можно сделать при определении поля так:

эквивалентно:

slug = forms.CharField(validators=[validators.validate_slug])

Обычные случаи, такие как проверка по электронной почте или регулярному выражению, могут быть обработаны с помощью существующих классов валидаторов, доступных в Django. Например, validators.validate_slug — это экземпляр RegexValidator, построенный с первым аргументом в виде шаблона: ^[-a-zA-Z0-9_]+$. Смотрите раздел writing validators, чтобы увидеть список того, что уже доступно, и пример того, как написать валидатор.

Очистка полей формы по умолчанию¶

Давайте сначала создадим поле пользовательской формы, которое проверяет, что его входные данные — это строка, содержащая адреса электронной почты, разделенные запятыми. Полный класс выглядит следующим образом:

from django import forms
from django.core.validators import validate_email

class MultiEmailField(forms.Field):
    def to_python(self, value):
        """Normalize data to a list of strings."""
        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')

    def validate(self, value):
        """Check if value consists only of valid emails."""
        # Use the parent's handling of required fields, etc.
        super().validate(value)
        for email in value:
            validate_email(email)

В каждой форме, использующей это поле, эти методы будут выполняться до того, как с данными поля можно будет сделать что-либо еще. Это очистка, специфичная для данного типа поля, независимо от того, как оно будет использоваться в дальнейшем.

Давайте создадим ContactForm, чтобы продемонстрировать, как вы будете использовать это поле:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    recipients = MultiEmailField()
    cc_myself = forms.BooleanField(required=False)

Используйте MultiEmailField как любое другое поле формы. Когда на форме будет вызван метод is_valid(), в процессе очистки будет запущен метод MultiEmailField.clean(), который, в свою очередь, вызовет пользовательские методы to_python() и validate().

Очистка определенного атрибута поля¶

Продолжая предыдущий пример, предположим, что в нашем ContactForm мы хотим убедиться, что поле recipients всегда содержит адрес "fred@example.com". Это проверка, специфичная для нашей формы, поэтому мы не хотим помещать ее в общий класс MultiEmailField. Вместо этого мы напишем метод очистки, который работает с полем recipients, следующим образом:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise ValidationError("You have forgotten about Fred!")

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data

Очистка и проверка полей, которые зависят друг от друга¶

Предположим, мы добавим еще одно требование к нашей контактной форме: если поле cc_myself является True, то subject должно содержать слово "help". Мы выполняем проверку более чем одного поля одновременно, поэтому метод формы clean() является хорошим местом для этого. Обратите внимание, что здесь мы говорим о методе clean() на форме, тогда как ранее мы писали метод clean() на поле. Важно четко различать поля и формы, когда мы решаем, где проводить валидацию. Поля — это отдельные точки данных, а формы — это набор полей.

К моменту вызова метода clean() формы будут запущены все методы очистки отдельных полей (предыдущие два раздела), поэтому self.cleaned_data будет заполнен любыми данными, которые сохранились до сих пор. Поэтому вам также нужно помнить о том, что поля, которые вы хотите проверить, могут не выдержать первоначальной проверки отдельных полей.

Есть два способа сообщить о любых ошибках на этом этапе. Вероятно, самый распространенный способ — вывести ошибку в верхней части формы. Чтобы создать такую ошибку, вы можете поднять ValidationError из метода clean(). Например:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

В этом коде, если возникает ошибка валидации, форма выводит сообщение об ошибке в верхней части формы (обычно) с описанием проблемы. Такие ошибки являются не-полевыми ошибками, которые отображаются в шаблоне с помощью {{ form.non_field_errors }}.

Вызов super().clean() в коде примера гарантирует, что любая логика валидации в родительских классах будет сохранена. Если ваша форма наследует другую, которая не возвращает словарь cleaned_data в своем методе clean() (это необязательно), то не присваивайте cleaned_data результату вызова super() и используйте self.cleaned_data вместо этого:

def clean(self):
    super().clean()
    cc_myself = self.cleaned_data.get("cc_myself")
    ...

Второй подход для сообщения об ошибках валидации может включать присвоение сообщения об ошибке одному из полей. В данном случае давайте присвоим сообщение об ошибке обеим строкам «subject» и «cc_myself» в отображении формы. Будьте осторожны, делая это на практике, так как это может привести к запутанному выводу формы. Мы показываем, что здесь возможно, и предоставляем вам и вашим дизайнерам самим решать, что будет эффективно работать в вашей конкретной ситуации. Наш новый код (заменяющий предыдущий пример) выглядит следующим образом:

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject and "help" not in subject:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)

Вторым аргументом add_error() может быть строка или, предпочтительно, экземпляр ValidationError. Более подробную информацию смотрите в Поднятие ValidationError. Обратите внимание, что add_error() автоматически удаляет поле из cleaned_data.

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(
                error_messages={
               'required': 'Please enter your name'
                })
>>> name.clean('')
Traceback (most recent call last):
  ...
ValidationError: ['Please enter your name']

Syntax

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.

  • How to Create a Basic Project using MVT in Django?
  • How to Create an App in Django ?

Enter the following code into forms.py 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

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'geeks',

]

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 views.py of geeks app,

from django.shortcuts import render

from .forms import GeeksForm

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")

            print(temp)

    return render(request, "home.html", context)

Here we are importing that particular form from forms.py 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">

</form>

Finally, a URL to map to this view in urls.py

from django.urls import path

from .views import home_view

URLpatterns = [

    path('', home_view ),

]

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

Python manage.py runserver

error_messages - Django Form Field Validation

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

error_messages-Django-Form-Field-Validation

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.

Понравилась статья? Поделить с друзьями:
  • Django form error text
  • Django form error messages
  • Django form error message
  • Django form error list
  • Django form error css