help_text – Django 内置字段验证
Django 模型中的内置字段验证是为所有 Django 字段预定义的验证。每个字段都带有来自 Django 验证器的内置验证。还可以添加更多内置字段验证,以在特定字段上应用或删除某些约束。
help_text
属性用于在管理界面或 ModelForm 中显示“帮助”文本以及表单中的字段。即使您的字段未在表单上使用,它对文档也很有用。例如,您可以在 DateField 的help_text
中定义要作为输入的日期模式。
句法-
field_name = models.Field(help_text = "text")
Django 内置字段验证help_text
解释
使用示例说明help_text 。考虑一个名为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
文件中输入以下代码。我们将使用 DateField 来试验 help_text。
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.DateField(
help_text = "Please use the following format: YYYY-MM-DD."
)
在 Django 上运行 makemigrations 和 migrate 并渲染上述模型后,让我们检查一下 Django 管理界面中的字段是否发生了什么事。
您可以在字段底部看到添加的额外文本。这是您可以修改要在 ModelForm 中的字段下方显示的文本。
带有help_text
的高级概念 –
=>我该怎么办,即使尝试了很多次,help_text 也没有显示?
将{{ form.as_p }}
(或只是{{ form }}
)放在您的模板中应该显示 help_text 而无需其他代码,前提是您的上下文中有表单,或者如果您使用单个字段,您可以使用{{ form.field.help_text }}
访问特定字段的帮助文本。
更多内置字段验证
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. |