内置字段验证 – Django 模型
Django 模型中的内置字段验证是为所有 Django 字段预定义的默认验证。每个字段都带有来自 Django 验证器的内置验证。例如, IntegerField 带有内置验证,它只能存储整数值并且也可以存储在特定范围内。同样,每个字段都有自己的验证。有关更多信息,请访问 Django 模型。
Django 中对字段的内置验证的演示
考虑一个名为 geeksforgeeks 的项目,它有一个名为 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 ?
在极客应用的models.py文件中输入以下代码。
Python3
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.IntegerField()
def __str__(self):
return self.geeks_field
在 Django 上运行 makemigrations 和 migrate 并渲染上述模型后,让我们尝试使用字符串“ GfG is Best ”创建一个实例。
您可以在管理界面中看到,无法在 IntegerField 中输入字符串。同样,每个字段都有自己的验证。
向字段添加更多内置验证
Django 为您想要存储在数据库中的几乎所有数据选择字段,例如 IntegerField 用于整数和 CharField 用于字符串。但也有一些内置验证可以应用于这些字段。例如,unique=True 会将特定字段的条目限制为唯一条目。以下是可用于字段进行更多更改的内置验证列表。Field Options Description Null If True, Django will store empty values as NULL in the database. Default is False. Blank If True, the field is allowed to be blank. Default is False. db_column The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
Default The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_text Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_key If True, this field is the primary key for the model. editable If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
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.
help_text Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
verbose_name A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validators A list of validators to run for this field. See the validators documentation for more information.
Unique If True, this field must be unique throughout the table.