verbose_name – Django 内置字段验证
Django 模型中的内置字段验证是为所有 Django 字段预定义的验证。每个字段都带有来自 Django 验证器的内置验证。还可以添加更多内置字段验证,以在特定字段上应用或删除某些约束。 verbose_name
是该字段的人类可读名称。如果没有给出详细名称,Django 将使用字段的属性名称自动创建它,将下划线转换为空格。此属性通常会更改管理界面中的字段名称。
句法 -
field_name = models.Field(verbose_name = "name")
Django内置字段验证verbose_name
解释
使用示例说明verbose_name 。考虑一个名为geeks
的项目,它有一个名为geeksforgeeks
的应用程序。
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
文件中输入以下代码。我们将使用 CharField 来试验所有字段选项。
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.CharField(
max_length = 200,
)
在 Django 上运行makemigrations
和 migrate 并渲染上述模型后,让我们检查geeks_field
的显示名称。
现在让我们使用verbose_name
属性来修改它。将models.py
更改为
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.CharField(
max_length = 200,
verbose_name = "Geeksforgeeks"
)
由于 models.py 已修改运行 makemigrations 并在项目上再次迁移。打开管理界面并再次检查该字段的名称,它已更改为“Geeksforgeeks”。
您可以看到修改后的图像。因此, verbose_name
修改了字段名称。
更多内置字段验证
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. |