Form介紹
我們之前在HTML頁面中利用form表單向后端提交數據時,都會寫一些獲取用戶輸入的標簽並且用form標簽把它們包起來。
與此同時我們在好多場景下都需要對用戶的輸入做校驗,比如校驗用戶是否輸入,輸入的長度和格式等正不正確。如果用戶輸入的內容有錯誤就需要在頁面上相應的位置顯示顯示對應的錯誤信息.。
Django form組件就實現了上面所述的功能。
總結一下,其實form組件的主要功能如下:
- 生成頁面可用的HTML標簽
- 對用戶提交的數據進行校驗
- 保留上次輸入內容
普通的登錄
views.py
def login(request): error_msg = "" if request.method == "POST": username = request.POST.get("username") pwd = request.POST.get("pwd") if username == "Q1mi" and pwd == "123456": return HttpResponse("OK") else: error_msg = "用戶名或密碼錯誤" return render(request, "login.html", {"error_msg": error_msg})
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>login</title> <style> .error { color: red; } </style> </head> <body> <form action="/login/" method="post"> {% csrf_token %} <p> <label for="username">用戶名</label> <input type="text" name="username" id="username"> </p> <p> <label for="pwd">密碼</label> <input type="password" name="pwd" id="pwd"> <span class="error"></span> </p> <p> <input type="submit"> <span class="error">{{ error_msg }}</span> </p> </form> </body> </html>
使用form組件
views.py
先定義好一個LoginForm類。
class LoginForm(forms.Form): username = forms.CharField(min_length=8, label="用戶名") pwd = forms.CharField(min_length=6, label="密碼") def login2(request): error_msg = "" form_obj = LoginForm() if request.method == "POST": form_obj = LoginForm(request.POST) if form_obj.is_valid(): username = form_obj.cleaned_data.get("username") pwd = form_obj.cleaned_data.get("pwd") if username == "Q1mi" and pwd == "123456": return HttpResponse("OK") else: error_msg = "用戶名或密碼錯誤" return render(request, "login2.html", {"form_obj": form_obj, "error_msg": error_msg})
login2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>login</title> <style> .error { color: red; } </style> </head> <body> <form action="/login2/" method="post" novalidate> {% csrf_token %} <p> {{ form_obj.username.label }} {{ form_obj.username }} <span class="error">{{ form_obj.username.errors.0 }}</span> </p> <p> {{ form_obj.pwd.label }} {{ form_obj.pwd }} <span class="error">{{ form_obj.pwd.errors.0 }}</span> </p> <p> <input type="submit"> <span class="error">{{ error_msg }}</span> </p> </form> </body> </html>
看網頁效果發現 也驗證了form的功能:
• 前端頁面是form類的對象生成的 -->生成HTML標簽功能
• 當用戶名和密碼輸入為空或輸錯之后 頁面都會提示 -->用戶提交校驗功能
• 當用戶輸錯之后 再次輸入 上次的內容還保留在input框 -->保留上次輸入內容
Form那些事兒
常用字段演示
initial
初始值,input框里面的初始值。initial 表示默認值
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三" # 設置默認值 ) pwd = forms.CharField(min_length=6, label="密碼")
error_messages
重寫錯誤信息。
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三", error_messages={ "required": "不能為空", #當該字段設置為非空時,不填就會返回,用於重寫為空時的提示 "invalid": "格式錯誤", #常用於email輸入的格式不正確時的提示信息 "min_length": "用戶名最短8位" } ) pwd = forms.CharField(min_length=6, label="密碼") #label 用於重寫該字段的名字
password
class LoginForm(forms.Form): ... pwd = forms.CharField( min_length=6, label="密碼", widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True) ) #render_value=True 表示輸入框校驗不通過時,保留當前輸入值
radioSelect
單radio值為字符串
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三", error_messages={ "required": "不能為空", "invalid": "格式錯誤", "min_length": "用戶名最短8位" } ) pwd = forms.CharField(min_length=6, label="密碼") gender = forms.fields.ChoiceField( choices=((1, "男"), (2, "女"), (3, "保密")), label="性別", initial=3, widget=forms.widgets.RadioSelect )
單選Select
class LoginForm(forms.Form): ... hobby = forms.fields.ChoiceField( choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ), label="愛好", initial=3, widget=forms.widgets.Select )
多選Select
class LoginForm(forms.Form): ... hobby = forms.fields.MultipleChoiceField( choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ), label="愛好", initial=[1, 3], widget=forms.widgets.SelectMultiple )
單選checkbox
class LoginForm(forms.Form): ... keep = forms.fields.ChoiceField( label="是否記住密碼", initial="checked", widget=forms.widgets.CheckboxInput )
多選checkbox
class LoginForm(forms.Form): ... hobby = forms.fields.MultipleChoiceField( choices=((1, "籃球"), (2, "足球"), (3, "雙色球"),), label="愛好", initial=[1, 3], widget=forms.widgets.CheckboxSelectMultiple )
關於choice的注意事項:
在使用選擇標簽時,需要注意choices的選項可以從數據庫中獲取,但是由於是靜態字段 ***獲取的值無法實時更新***,那么需要自定義構造方法從而達到此目的。
方式一:
from django.forms import Form from django.forms import widgets from django.forms import fields class MyForm(Form): user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), initial=2, widget=widgets.Select ) def __init__(self, *args, **kwargs): super(MyForm,self).__init__(*args, **kwargs) # self.fields['user'].widget.choices = ((1, '上海'), (2, '北京'),) # 或 self.fields['user'].widget.choices = models.Classes.objects.all().values_list('id','caption')
方式二:
from django import forms from django.forms import fields from django.forms import models as form_model class FInfo(forms.Form): authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())

Field required=True, 是否允許為空 widget=None, HTML插件 label=None, 用於生成Label標簽或顯示內容 initial=None, 初始值 help_text='', 幫助信息(在標簽旁邊顯示) error_messages=None, 錯誤信息 {'required': '不能為空', 'invalid': '格式錯誤'} show_hidden_initial=False, 是否在當前插件后面再加一個隱藏的且具有默認值的插件(可用於檢驗兩次輸入是否一直) validators=[], 自定義驗證規則 localize=False, 是否支持本地化 disabled=False, 是否可以編輯 label_suffix=None Label內容后綴 CharField(Field) max_length=None, 最大長度 min_length=None, 最小長度 strip=True 是否移除用戶輸入空白 IntegerField(Field) max_value=None, 最大值 min_value=None, 最小值 FloatField(IntegerField) ... DecimalField(IntegerField) max_value=None, 最大值 min_value=None, 最小值 max_digits=None, 總長度 decimal_places=None, 小數位長度 BaseTemporalField(Field) input_formats=None 時間格式化 DateField(BaseTemporalField) 格式:2015-09-01 TimeField(BaseTemporalField) 格式:11:12 DateTimeField(BaseTemporalField)格式:2015-09-01 11:12 DurationField(Field) 時間間隔:%d %H:%M:%S.%f ... RegexField(CharField) regex, 自定制正則表達式 max_length=None, 最大長度 min_length=None, 最小長度 error_message=None, 忽略,錯誤信息使用 error_messages={'invalid': '...'} EmailField(CharField) ... FileField(Field) allow_empty_file=False 是否允許空文件 ImageField(FileField) ... 注:需要PIL模塊,pip3 install Pillow 以上兩個字典使用時,需要注意兩點: - form表單中 enctype="multipart/form-data" - view函數中 obj = MyForm(request.POST, request.FILES) URLField(Field) ... BooleanField(Field) ... NullBooleanField(BooleanField) ... ChoiceField(Field) ... choices=(), 選項,如:choices = ((0,'上海'),(1,'北京'),) required=True, 是否必填 widget=None, 插件,默認select插件 label=None, Label內容 initial=None, 初始值 help_text='', 幫助提示 ModelChoiceField(ChoiceField) ... django.forms.models.ModelChoiceField queryset, # 查詢數據庫中的數據 empty_label="---------", # 默認空顯示內容 to_field_name=None, # HTML中value的值對應的字段 limit_choices_to=None # ModelForm中對queryset二次篩選 ModelMultipleChoiceField(ModelChoiceField) ... django.forms.models.ModelMultipleChoiceField TypedChoiceField(ChoiceField) coerce = lambda val: val 對選中的值進行一次轉換 empty_value= '' 空值的默認值 MultipleChoiceField(ChoiceField) ... TypedMultipleChoiceField(MultipleChoiceField) coerce = lambda val: val 對選中的每一個值進行一次轉換 empty_value= '' 空值的默認值 ComboField(Field) fields=() 使用多個驗證,如下:即驗證最大長度20,又驗證郵箱格式 fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),]) MultiValueField(Field) PS: 抽象類,子類中可以實現聚合多個字典去匹配一個值,要配合MultiWidget使用 SplitDateTimeField(MultiValueField) input_date_formats=None, 格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y'] input_time_formats=None 格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'] FilePathField(ChoiceField) 文件選項,目錄下文件顯示在頁面中 path, 文件夾路徑 match=None, 正則匹配 recursive=False, 遞歸下面的文件夾 allow_files=True, 允許文件 allow_folders=False, 允許文件夾 required=True, widget=None, label=None, initial=None, help_text='' GenericIPAddressField protocol='both', both,ipv4,ipv6支持的IP格式 unpack_ipv4=False 解析ipv4地址,如果是::ffff:192.0.2.1時候,可解析為192.0.2.1, PS:protocol必須為both才能啟用 SlugField(CharField) 數字,字母,下划線,減號(連字符) ... UUIDField(CharField) uuid類型
備注:UUID是根據MAC以及當前時間等創建的不重復的隨機字符串

>>> import uuid # make a UUID based on the host ID and current time >>> uuid.uuid1() # doctest: +SKIP UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') # make a UUID using an MD5 hash of a namespace UUID and a name >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') # make a random UUID >>> uuid.uuid4() # doctest: +SKIP UUID('16fd2706-8baf-433b-82eb-8c7fada847da') # make a UUID using a SHA-1 hash of a namespace UUID and a name >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') # make a UUID from a string of hex digits (braces and hyphens ignored) >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') # convert a UUID to a string of hex digits in standard form >>> str(x) '00010203-0405-0607-0809-0a0b0c0d0e0f' # get the raw 16 bytes of the UUID >>> x.bytes b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' # make a UUID from a 16-byte string >>> uuid.UUID(bytes=x.bytes) UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
備注:在Django中要區分開models.Model、forms.Form、ModelForm,這三個中,model.Model是django中的模型表,自定義一個類,類的屬性就是字段的屬性,包括一些普通的字段屬性(比如:CharField、DecimalField等)和一些特殊的字段屬性(比如:一對多ForeignKey,多對多字段ManyToLMany和一對一字段OneToOne(特殊的Foreignkey))。forms.Form使用於校驗字段,生成HTML標簽,展示錯誤信息,常用於注冊 和 一些校驗頁面比如:添加頁面和編輯頁面。同樣的,在forms.Form中也有一些特殊的字段屬性,它也是自定義一個類,類的屬性就是每一個字段的屬性,不同的是:models.Model是數據庫的模型類,而forms.Form則和數據庫沒有任何的關系。他也有普通的字段(比如:CharField等),但是在forms.Form中沒有ForeignKey、ManyToMany等這些字段,相對應的,他有一個ChoiceField,生成對應的select標簽,但是有一個弊端,無法及時更新數據,每次數據庫發生變動,不能及時的做出反應,針對於此,繼承ChoiceField類生成了兩個對應models.Model中ForeignKey和ManyToMany,一個是ModelChoiceField(ChoiceField)繼承ChoiceField,對應ForeignKey,另外一個是ModelMuiltChoiceField(ModelChoiceField),繼承ModelChoiceField,對應ManyToMany。這兩個字段避免了數據的無法實時更新。最后一個ModelForm,是一個特殊的,它是連接數據庫models.Model和forms.Form之間的一個特殊的中間的東西,它是將models.Model中的字段全部轉化為forms.Form中的字段,然后自動生成HTMl和校驗字段。

#forms.widgets字段 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
校驗
方式一:
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( validators=[RegexValidator(r'^[0-9]+$', '請輸入數字'), RegexValidator(r'^159[0-9]+$', '數字必須以159開頭')], )
方式二:
import re from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.exceptions import ValidationError # 自定義驗證規則 def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手機號碼格式錯誤') class PublishForm(Form): title = fields.CharField(max_length=20, min_length=5, error_messages={'required': '標題不能為空', 'min_length': '標題最少為5個字符', 'max_length': '標題最多為20個字符'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': '標題5-20個字符'})) # 使用自定義驗證規則 phone = fields.CharField(validators=[mobile_validate, ], error_messages={'required': '手機不能為空'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'手機號碼'})) email = fields.EmailField(required=False, error_messages={'required': u'郵箱不能為空','invalid': u'郵箱格式錯誤'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))
方法三:自定義方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
from
django
import
forms
from
django.forms
import
fields
from
django.forms
import
widgets
from
django.core.exceptions
import
ValidationError
from
django.core.validators
import
RegexValidator
class
FInfo(forms.Form):
username
=
fields.CharField(max_length
=
5
,
validators
=
[RegexValidator(r
'^[0-9]+$'
,
'Enter a valid extension.'
,
'invalid'
)], )
email
=
fields.EmailField()
def
clean_username(
self
):
"""
Form中字段中定義的格式匹配完之后,執行此方法進行驗證
:return:
"""
value
=
self
.cleaned_data[
'username'
]
if
"666"
in
value:
raise
ValidationError(
'666已經被玩爛了...'
,
'invalid'
)
return
value
|
方式四:同時生成多個標簽進行驗證
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
from
django.forms
import
Form
from
django.forms
import
widgets
from
django.forms
import
fields
from
django.core.validators
import
RegexValidator
############## 自定義字段 ##############
class
PhoneField(fields.MultiValueField):
def
__init__(
self
,
*
args,
*
*
kwargs):
# Define one message for all fields.
error_messages
=
{
'incomplete'
:
'Enter a country calling code and a phone number.'
,
}
# Or define a different message for each field.
f
=
(
fields.CharField(
error_messages
=
{
'incomplete'
:
'Enter a country calling code.'
},
validators
=
[
RegexValidator(r
'^[0-9]+$'
,
'Enter a valid country calling code.'
),
],
),
fields.CharField(
error_messages
=
{
'incomplete'
:
'Enter a phone number.'
},
validators
=
[RegexValidator(r
'^[0-9]+$'
,
'Enter a valid phone number.'
)],
),
fields.CharField(
validators
=
[RegexValidator(r
'^[0-9]+$'
,
'Enter a valid extension.'
)],
required
=
False
,
),
)
super
(PhoneField,
self
).__init__(error_messages
=
error_messages, fields
=
f, require_all_fields
=
False
,
*
args,
*
*
kwargs)
def
compress(
self
, data_list):
"""
當用戶驗證都通過后,該值返回給用戶
:param data_list:
:return:
"""
return
data_list
############## 自定義插件 ##############
class
SplitPhoneWidget(widgets.MultiWidget):
def
__init__(
self
):
ws
=
(
widgets.TextInput(),
widgets.TextInput(),
widgets.TextInput(),
)
super
(SplitPhoneWidget,
self
).__init__(ws)
def
decompress(
self
, value):
"""
處理初始值,當初始值initial不是列表時,調用該方法
:param value:
:return:
"""
if
value:
return
value.split(
','
)
return
[
None
,
None
,
None
]
|
補充進階
應用Bootstrap樣式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> <title>login</title> </head> <body> <div class="container"> <div class="row"> <form action="/login2/" method="post" novalidate class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="{{ form_obj.username.id_for_label }}" class="col-md-2 control-label">{{ form_obj.username.label }}</label> <div class="col-md-10"> {{ form_obj.username }} <span class="help-block">{{ form_obj.username.errors.0 }}</span> </div> </div> <div class="form-group"> <label for="{{ form_obj.pwd.id_for_label }}" class="col-md-2 control-label">{{ form_obj.pwd.label }}</label> <div class="col-md-10"> {{ form_obj.pwd }} <span class="help-block">{{ form_obj.pwd.errors.0 }}</span> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">{{ form_obj.gender.label }}</label> <div class="col-md-10"> <div class="radio"> {% for radio in form_obj.gender %} <label for="{{ radio.id_for_label }}"> {{ radio.tag }}{{ radio.choice_label }} </label> {% endfor %} </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">注冊</button> </div> </div> </form> </div> </div> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> </body> </html>
批量添加樣式
可通過重寫form類的init方法來實現。

class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三", error_messages={ "required": "不能為空", "invalid": "格式錯誤", "min_length": "用戶名最短8位" } ... def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' })
在template模板中的使用
1.實例化一個form_obj 我們可以對我們創建的類進行實例化,將這個對象傳到前端 比如:form_obj = RegForm()
這個form_obj是一個包含所有對象和字段屬性的對象,我們可以在模板HTML中,使用三種方式去生成html代碼
1,直接form_obj.as_p(或者as_table\as_li等) 直接幫我們生成一個包含label和對應input的p標簽
2,我們可以逐個的生成每一個HTML
<div class="form-group {% if form_obj.password.errors.0 %}has-error{% endif %}"> <div class="col-sm-2 control-label">{{ form_obj.password.label }}</div> <div class="col-sm-10 input-group"> {{ form_obj.password }} <span class="help-block">{{ form_obj.password.errors.0 }}</span> </div> </div>
3.我們也可以for循環這個form_obj對象,批量的生成HTML代碼
循環這個form_obj.fields,可以取出當中的每一個字段。
{% for foo in form_obj %} <div class="form-group {% if foo.errors.0 %}has-error{% endif %}"> <label for="{{ foo.id_for_label }}" class="col-md-2 control-label">{{ foo.label }}</label> <div class="col-md-8"> {{ foo }} </div> <span class="help-block">{{ foo.errors.0 }}</span> </div> {% endfor %}
我們也可以使用for循環整體的取出
{% for field in form_obj %}
{{ field.label }}
{{ field }}
{{ field.errors.0 }}
{% endfor %}
使用post請求提交數據時,我們可以通過將這個request.POST 當成參數傳到實例化這個對象中,比如:form_obj=RegForm(request.POST)。然后我們通過form_obj.is_valid()這個方法對用戶提交的數據進行校驗,得到一個bool值,我們可以通過這個bool值,進行相應的操作,我們可以在校驗通過后通過form_obj.cleaned_data這個屬性方法,按照字典的key進行取值。
備注:在給form_obj=RegForm(),括號中傳參時,傳的是一個字典類型的數據,由於request.POST、request.FILES等這些輸出為一個字典,所以可以直接將其作為參數傳給form_obj。is_valid校驗時,從這個數據字典中取RegForm這個類中的字段,取不到,直接添加error給form_obj.errors這個ErrorDict。