📜  必需 - Django 表单字段验证

📅  最后修改于: 2022-05-13 01:55:35.216000             🧑  作者: Mango

必需 - Django 表单字段验证

Django 表单中的内置表单字段验证是为所有字段预定义的默认验证。每个字段都带有来自 Django 验证器的一些内置验证。每个 Field 类的构造函数都有一些固定的参数。一些 Field 类采用额外的、特定于字段的参数,但应该始终接受 required 。

required通常用于使该字段成为可选字段,即用户不再需要将数据输入该字段并且仍将被接受。让我们检查如何使用项目在字段中使用所需的用户。

句法

field_name = models.Field(option = value)

Django 表单字段验证required说明

需要使用示例进行说明。考虑一个名为geeks的项目,它有一个名为geeksforgeeks的应用程序。

geeks app的forms.py文件中输入以下代码。我们将使用 CharField 来试验所有字段选项。

from django import forms
  
class GeeksForm(forms.Form):
    geeks_field = forms.CharField(required = False)

将极客应用添加到INSTALLED_APPS

# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]

现在要将这个表单渲染到一个视图中,我们需要一个视图和一个映射到该视图的 URL。我们先在geeks app的views.py中创建一个视图,

from django.shortcuts import render
from .forms import GeeksForm
  
# Create your views here.
def home_view(request):
    context = {}
    form = GeeksForm(request.POST or None)
    context['form'] = form
    if request.POST:
        if form.is_valid():
            temp = form.cleaned_data.get("geeks_field")
            print(temp)
    return render(request, "home.html", context)

在这里,我们从 forms.py 导入该特定表单并在视图中创建它的对象,以便可以在模板中呈现它。
现在,要启动一个 Django 表单,您需要创建 home.html,在其中可以根据需要设计内容。让我们在home.html中创建一个表单。

    {% csrf_token %}     {{ form }}     

最后,在 urls.py 中映射到该视图的 URL

from django.urls import path
  
# importing views from views..py
from .views import home_view
  
URLpatterns = [
    path('', home_view ),
]

让我们运行服务器并检查实际发生了什么,运行

Python manage.py runserver

django-form-validations

因此,通过将“_”替换为“”来创建geeks_field CharField

如何在 Django 表单字段中使用 required ?

required通常用于使该字段成为可选字段,即用户不再需要将数据输入该字段并且仍将被接受。让我们检查如何在使用项目的字段中使用 required。当设置为特定值时,使用的选项会根据开发人员的要求将一些验证附加到该字段。

让我们尝试通过我们创建的 Django Web 应用程序使用 required,访问 http://localhost:8000/ 并尝试根据字段上应用的选项或验证输入值。点击提交。

django-forms-required-validation

因此,即使 geeks_field 中没有任何数据,Field 也会接受该表单。这使得required=False成功实施。

更多内置表单验证

Field OptionsDescription
requiredBy default, each Field class assumes the value is required, so to make it not required you need to set required=False
labelThe label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
label_suffixThe label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widgetThe widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_textThe help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods.
error_messagesThe 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.
validatorsThe validators argument lets you provide a list of validation functions for this field.
localizeThe localize argument enables the localization of form data input, as well as the rendered output.
disabled.The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users.