Table of Contents
Sometimes Django model fields need to be validated against harmful input data that may cause issues in DB layer. Django ORM cannot handle these kind of issues all time, as DB driver (wrapper) often raises technical error reports. To avoid this errors model fields must be validated in model layer instead of validating view or form validation parts.
Why this is important #
This is important because, if you validate input data in view layer, other API endpoints may also access model manager at same time to make changes. At this time you will loose very important data for saving in DB. Validating input fields in model layer is useful as it can be executed at any higher layers since your web application codebase uses your pre-defined models everywhere.
Let's create simple example model with username and password field validation.
from django.core import validators from django.db import models username_validator = validators.RegexValidator( r'^[\w.@+-]+$', _('Enter a valid username.'), ) class User(models.Model): username = models.CharField( _('username'), max_length=30, unique=True, help_text=_('@/./+/-/_ only allowed.'), validators=[username_validator], )