Django Form
借助 Django 的 Form 可以很容易的完成:
- 生成 HTML 标签
- 验证用户数据(显示错误信息)
- HTML Form 提交后保留上次提交数据
- 初始化页面显示内容
Form 类
- Form 类中包含字段,字段用于用户请求验证。
Django 内置字段
- 字段中封装了插件,插件用于自动生成 HTML。
Django 内置插件
TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget
常用选择插件:
# 单radio,值为字符串
location = fields.CharField(
initial=2,
widget=widgets.RadioSelect(choices=((1,'Beijing'),(2,'Shanghai'),))
)
# 单radio,值为字符串
location = fields.ChoiceField(
choices=((1, 'Beijing'), (2, 'Shanghai'),),
initial=2,
widget=widgets.RadioSelect
)
# 单select,值为字符串
location = fields.CharField(
initial=2,
widget=widgets.Select(choices=((1,'Beijing'),(2,'Shanghai'),))
)
# 单select,值为字符串
location = fields.ChoiceField(
choices=((1, 'Beijing'), (2, 'Shanghai'),),
initial=2,
widget=widgets.Select
)
# 多选select,值为列表
location = fields.MultipleChoiceField(
choices=((1,'Beijing'),(2,'Shanghai'),),
initial=[1,],
widget=widgets.SelectMultiple
)
# 单checkbox
location = fields.CharField(
widget=widgets.CheckboxInput()
)
# 多选checkbox,值为列表
location = fields.MultipleChoiceField(
initial=[2, ],
choices=((1, 'Beijing'), (2, 'Shanghai'),),
widget=widgets.CheckboxSelectMultiple
)
初始化数据
初始化只需在实例化 Form 类时,将包含数据的字典传入。
示例:
form:
from django import forms
from django.forms import widgets, fields
class CustomForm(forms.Form):
name = fields.CharField(
max_length=20,
error_messages={'request': '用户名不能为空'},
label='Username:',
)
location = fields.ChoiceField(
choices=((1, 'Beijing'), (2, 'Shanghai')),
label='location',
)
views:
from django.shortcuts import render
def form(request):
if request.method == 'GET':
dict = {
'name': 'user',
'location': 1,
}
obj = CustomForm(dict)
return render(request, 'form.html', {'obj': obj})
HTML:
<form action="/form.html" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ obj.user }} {{ obj.errors.user.0 }}</p>
<p>{{ obj.location }}</p>
<input type="submit" value="submit"/>
</form>