Django
Model field validation
#
Find similar titles
- (rev. 1)
- Hyungyong Kim
Structured data
- Category
- Etc
- Programming
- Database
Table of Contents
Introduction #
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.
Implementation #
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],
)
Reference #
https://docs.djangoproject.com/en/1.8/ref/validators/
Incoming Links #
Related Articles (Article 0) #
Suggested Pages #
- 0.298 pcr
- 0.138 question test1
- 0.053 예시페이지
- 0.046 flutter
- 0.040 bacteriophage
- 0.034 바이오잉크
- 0.025 파이썬
- 0.025 이클립스
- 0.025 MVT
- 0.024 Jython
- More suggestions...