Django 表单
创建Form类时,最重要的部分是定义表单的字段。每个字段都有自定义验证逻辑,以及一些其他钩子。本文围绕可以在表单中使用的各种字段以及与 Django Forms 相关的各种功能和技术展开。表单基本上用于以某种方式从用户那里获取输入,并将该信息用于数据库的逻辑操作。例如,通过输入用户的姓名、电子邮件、密码等来注册用户。
Django 将 Django 表单中定义的字段映射到 HTML 输入字段。 Django 处理表单中涉及的三个不同部分的工作:
- 准备和重组数据以使其准备好进行渲染
- 为数据创建 HTML 表单
- 接收和处理客户提交的表格和数据
请注意,由 Django 表单完成的所有类型的工作都可以使用高级 HTML 内容完成,但 Django 使它更容易和高效,尤其是验证部分。一旦你掌握了 Django 表单,你就会忘记 HTML 表单。
语法: Django Fields 像 Django Model Fields 一样工作,语法如下:
field_name = forms.FieldType(**options)
例子:
Python3
from django import forms
# creating a form
class GeeksForm(forms.Form):
title = forms.CharField()
description = forms.CharField()
Python3
# import the standard Django Forms
# from built-in library
from django import forms
# creating a form
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())
Python3
from django.shortcuts import render
from .forms import InputForm
# Create your views here.
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "home.html", context)
html
Python3
# import the standard Django Model
# from built-in library
from django.db import models
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
last_modified = models.DateTimeField(auto_now_add = True)
img = models.ImageField(upload_to = "images/")
# renames the instances of the model
# with their title name
def __str__(self):
return self.title
Python3
# import form class from django
from django import forms
# import GeeksModel from models.py
from .models import GeeksModel
# create a ModelForm
class GeeksForm(forms.ModelForm):
# specify the name of model to use
class Meta:
model = GeeksModel
fields = "__all__"
使用 Django 表单
要使用 Django Forms,需要有一个项目和一个在其中工作的应用程序。启动应用程序后,您可以在 app/forms.py 中创建一个表单。在开始使用表单之前,让我们检查一下如何启动项目并实现 Django Forms。
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 ?
创建 Django 表单
在 Django 中创建表单与创建模型完全相似,需要指定表单中存在哪些字段以及类型。例如,要输入注册表单,可能需要名字 (CharField)、卷号 (IntegerField) 等。
句法:
from django import forms
class FormName(forms.Form):
# each field would be mapped as an input field in HTML
field_name = forms.Field(**options)
创建表单,在 geeks/forms.py 中输入代码,
Python3
# import the standard Django Forms
# from built-in library
from django import forms
# creating a form
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())
要了解有关如何使用 Django 表单创建表单的更多信息,请访问如何使用 Django 表单创建表单?。
渲染 Django 表单
Django 表单字段有几种内置方法可以简化开发人员的工作,但有时需要手动实现一些东西来自定义用户界面(UI)。表单带有 3 个内置方法,可用于呈现 Django 表单字段。
- {{ form.as_table }} 会将它们呈现为包裹在
标签中的表格单元格 - {{ form.as_p }} 会将它们呈现在
标签中
- {{ form.as_ul }} 会将它们呈现在
- 标签中
要将此表单呈现为视图,请移至 views.py 并创建一个 home_view,如下所示。
Python3
from django.shortcuts import render from .forms import InputForm # Create your views here. def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context)
在视图中,只需在 forms.py 中创建上面创建的表单类的一个实例。现在让我们编辑模板 > home.html
html
现在,访问 http://localhost:8000/
.
要检查如何使用 Django Forms 呈现的数据,请访问 Render Django Form Fields从模型创建 Django 表单
Django ModelForm 是一个用于将模型直接转换为 Django 表单的类。如果您正在构建一个数据库驱动的应用程序,那么您很可能拥有与 Django 模型紧密映射的表单。现在,当我们准备好项目后,在 geeks/models.py 中创建一个模型,
Python3
# import the standard Django Model # from built-in library from django.db import models # declare a new model with a name "GeeksModel" class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() last_modified = models.DateTimeField(auto_now_add = True) img = models.ImageField(upload_to = "images/") # renames the instances of the model # with their title name def __str__(self): return self.title
要直接为此模型创建表单,请进入 geeks/forms.py 并输入以下代码:
Python3
# import form class from django from django import forms # import GeeksModel from models.py from .models import GeeksModel # create a ModelForm class GeeksForm(forms.ModelForm): # specify the name of model to use class Meta: model = GeeksModel fields = "__all__"
现在访问http://127.0.0.1:8000/,
更多关于 Django 表单:
- 在 Django 中呈现 HTML 表单(GET 和 POST)
- {{ form.as_p }} – 将 Django 表单渲染为段落
- {{ form.as_table }} – 将 Django 表单呈现为表格
- {{ form.as_ul }} – 将 Django 表单呈现为列表
- Django 表单字段自定义小部件
- Python|使用 django 进行表单验证
- Django ModelForm – 从模型创建表单
- 手动渲染 Django 表单字段
- Django 表单集
- Django 模型表单集
基本表单数据类型和字段列表
表单中最重要的部分也是唯一需要的部分是它定义的字段列表。字段由类属性指定。这是 Django 中使用的所有表单字段类型的列表
Name Class HTML Input BooleanField class BooleanField(**kwargs) CheckboxInput CharField class CharField(**kwargs) TextInput ChoiceField class ChoiceField(**kwargs) Select TypedChoiceField class TypedChoiceField(**kwargs) Select DateField class DateField(**kwargs) DateInput DateTimeField class DateTimeField(**kwargs) DateTimeInput DecimalField class DecimalField(**kwargs) NumberInput when Field.localize is False, else TextInput DurationField class DurationField(**kwargs) TextInput EmailField class EmailField(**kwargs EmailInput FileField class FileField(**kwargs) ClearableFileInput FilePathField class FilePathField(**kwargs) Select FloatField class FloatField(**kwargs) NumberInput when Field.localize is False, else TextInput ImageField class ImageField(**kwargs) ClearableFileInput IntegerField class IntegerField(**kwargs) NumberInput when Field.localize is False, else TextInput GenericIPAddressField class GenericIPAddressField(**kwargs) TextInput MultipleChoiceField class MultipleChoiceField(**kwargs) SelectMultiple TypedMultipleChoiceField class TypedMultipleChoiceField(**kwargs) SelectMultiple NullBooleanField class NullBooleanField(**kwargs) NullBooleanSelect RegexField class RegexField(**kwargs) TextInput SlugField class SlugField(**kwargs) TextInput TimeField class TimeField(**kwargs) TimeInput URLField class URLField(**kwargs) URLInput UUIDField class UUIDField(**kwargs) TextInput 核心字段参数
核心字段参数是赋予每个字段以应用某些约束或将特定特征赋予特定字段的参数。例如,向 CharField 添加参数 required = False 将使用户可以将其留空。每个 Field 类构造函数至少采用这些参数。一些 Field 类采用额外的、特定于字段的参数,但应始终接受以下参数:
.math-table { 边框折叠:折叠;宽度:100%; } .math-table td { 边框:1px 实心 #5fb962;文本对齐:左!重要;填充:8px; } .math-table th { 边框:1px 实心 #5fb962;填充:8px; } .math-table tr>th{ 背景颜色:#c6ebd9;垂直对齐:中间; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
Field Options Description required By default, each Field class assumes the value is required, so to make it not required you need to set required=False label The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form. label_suffix The label_suffix argument lets you override the form’s label_suffix on a per-field basis. widget The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information. help_text The 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_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. validators The validators argument lets you provide a list of validation functions for this field.
localize The 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.
- {{ form.as_p }} 会将它们呈现在