瀏覽目錄
-
Form介紹css
- 普通的登陸
- 使用form組件
-
Form詳情html
-
經常使用字段前端
-
校驗python
-
進階jquery
-
- 使用Django Form流程
1、Form介紹
咱們以前在HTML頁面中利用form表單向後端提交數據時,都會寫一些獲取用戶輸入的標籤而且用form標籤把它們包起來。git
與此同時咱們在好多場景下都須要對用戶的輸入作校驗,好比校驗用戶是否輸入,輸入的長度和格式等正不正確。若是用戶輸入的內容有錯誤就須要在頁面上相應的位置顯示顯示對應的錯誤信息.。正則表達式
Django form組件就實現了上面所述的功能。數據庫
總結一下,其實form組件的主要功能以下:django
- 生成頁面可用的HTML標籤
- 對用戶提交的數據進行校驗
- 保留上次輸入內容
- 自動生成錯誤信息
- 自動建立input標籤並設置樣式
一、普通的登陸
views.py
1
2
3
4
5
6
7
8
9
10
|
def
login(request):
error_msg
=
""
if
request.method
=
=
"POST"
:
username
=
request.POST.get(
"username"
)
pwd
=
request.POST.get(
"pwd"
)
if
username
=
=
yaya
" and pwd == "
123456
":
return
HttpResponse(
"OK"
)
else
:
error_msg
=
"用戶名或密碼錯誤"
return
render(request,
"login.html"
, {
"error_msg"
: error_msg})
|
login.html
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
|
<!
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組件
先定義好一個LoginForm類。bootstrap
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
=
=
"yaya"
and
pwd
=
=
"123456"
:
return
HttpResponse(
"OK"
)
else
:
error_msg
=
"用戶名或密碼錯誤"
return
render(request,
"login2.html"
, {
"form_obj"
: form_obj,
"error_msg"
: error_msg})
|
login.html
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
|
<!
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" 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框 -->保留上次輸入內容
2、Form詳情
一、經常使用字段
initial
初始值,input框裏面的初始值。
1
2
3
4
5
6
7
|
class
LoginForm(forms.Form):
username
=
forms.CharField(
min_length
=
8
,
label
=
"用戶名"
,
initial
=
"張三"
# 設置默認值
)
pwd
=
forms.CharField(min_length
=
6
, label
=
"密碼"
)
|
error_messages
重寫錯誤信息。
1
2
3
4
5
6
7
8
9
10
11
12
|
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
=
"密碼"
)
|
password
input框的type轉換爲password類型。
1
2
3
4
5
6
7
|
class
LoginForm(forms.Form):
...
pwd
=
forms.CharField(
min_length
=
6
,
label
=
"密碼"
,
widget
=
forms.widgets.PasswordInput(attrs
=
{
'class'
:
'c1'
}, render_value
=
True
)
)
|
radioSelect
單radio值爲字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
單選的選擇框
1
2
3
4
5
6
7
8
|
class
LoginForm(forms.Form):
...
hobby
=
forms.fields.ChoiceField(
choices
=
((
1
,
"籃球"
), (
2
,
"足球"
), (
3
,
"雙色球"
), ),
label
=
"愛好"
,
initial
=
3
,
widget
=
forms.widgets.Select
)
|
多選Select
多選的選擇框
1
2
3
4
5
6
7
8
|
class
LoginForm(forms.Form):
...
hobby
=
forms.fields.MultipleChoiceField(
choices
=
((
1
,
"籃球"
), (
2
,
"足球"
), (
3
,
"雙色球"
), ),
label
=
"愛好"
,
initial
=
[
1
,
3
],
widget
=
forms.widgets.SelectMultiple
)
|
單選checkbox
單選下拉框
1
2
3
4
5
6
7
|
class
LoginForm(forms.Form):
...
keep
=
forms.fields.ChoiceField(
label
=
"是否記住密碼"
,
initial
=
"checked"
,
widget
=
forms.widgets.CheckboxInput
)
|
多選checkbox
多選下拉框
1
2
3
4
5
6
7
8
|
class
LoginForm(forms.Form):
...
hobby
=
forms.fields.MultipleChoiceField(
choices
=
((
1
,
"籃球"
), (
2
,
"足球"
), (
3
,
"雙色球"
),),
label
=
"愛好"
,
initial
=
[
1
,
3
],
widget
=
forms.widgets.CheckboxSelectMultiple
)
|
關於choice的注意事項:
在使用選擇標籤時,須要注意choices的選項能夠從數據庫中獲取,可是因爲是靜態字段 ***獲取的值沒法實時更新***,那麼須要自定義構造方法從而達到此目的。
方式一:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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'
)
|
方式二:
1
2
3
4
5
6
7
8
|
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類型
二、校驗
方式一
1
2
3
4
5
6
7
8
9
|
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開頭'
)],
)
|
方式二
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
|
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
'郵箱'
}))
|
三、進階
應用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' })
3、使用Django Form流程
一、urls.py配置關係映射
二、views.py中建立Form類,定義字段的校驗條件,在映射關係中實例化Form類,進行邏輯處理,將Form對象經過響應Response返回頁面中
三、頁面中調用實例化Form對象進行操做
form對象渲染樣式:
方式一
1
2
3
|
{{ form.as_table }} 以表格的形式將它們渲染在<tr> 標籤中
{{ form.as_p }} 將它們渲染在<p> 標籤中
{{ form.as_ul }} 將它們渲染在<li> 標籤中
|
總體導入,應用不方便沒有特殊樣式。
方式二
1
|
{{form.user}}
|
優勢:使用方便,隨意修改特殊樣式;
缺點:若是標籤太多,操做會很麻煩。
方式三
1
2
3
4
5
6
7
8
|
{
%
for
field
in
form
%
}
<div>
<label
for
=
"">{{ field.label }}<
/
label>
<div>
{{ field }}
<
/
div>
<
/
div>
{
%
endfor
%
}
|
for循環,代碼簡捷,操做方便,效率高,但不便添加特殊樣式。
示例:註冊
from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/', views.register), ]
#models裏面建表 class UserInfo(models.Model): user = models.CharField(max_length=32) pwd = models.CharField(max_length=32) def __str__(self): return self.user
#在項目裏新建forms.py from django import forms class RegisterForm(forms.Form): user = forms.CharField( min_length=6, label="用戶名", error_messages={ "required": "用戶名不能爲空", "min_length": "用戶名不能小於6位", } ) pwd = forms.CharField( label="密碼", min_length=6, error_messages={ "required": "密碼不能爲空", "min_length": "密碼不能小於6位", }, widget=forms.widgets.PasswordInput() )
from django.shortcuts import render, HttpResponse from app01 import forms, models # Create your views here. def register(request): # 實例化一個form示例 form_obj = forms.RegisterForm() if request.method == "POST": # 把POST提交過來的數據傳到form表單裏 form_obj = forms.RegisterForm(request.POST) # 調用實例化對象的is_valid()方法,幫我作校驗! if form_obj.is_valid(): # 校驗經過 # form_obj.cleaned_data <-- 全部有效的數據都存放在cleaned_data屬性中 # user = form_obj.cleaned_data.get("user") # pwd = form_obj.cleaned_data.get("pwd") # 調用ORM,在數據庫中建立新的用戶 # models.UserInfo.objects.create(user=user, pwd=pwd) # print(form_obj.cleaned_data) models.UserInfo.objects.create(**form_obj.cleaned_data) return HttpResponse("O98K") # else: # # 校驗失敗 # # 此時,form_obj.errors 裏面保存了報錯的信息 # return render(request, "register.html", {"form_obj": form_obj}) return render(request, "register.html", {"form_obj": form_obj})
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>歡迎註冊!</h1> <form action="" method="post" novalidate> {% csrf_token %} <p> <label for="{{ form_obj.user.id_for_label }}">{{ form_obj.user.label }}</label> {{ form_obj.user }} <span>{{ form_obj.user.errors.0 }}</span> </p> <p> <label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label> {{ form_obj.pwd }} <span>{{ form_obj.pwd.errors.0 }}</span> </p> <p> <input type="submit" value="註冊"> </p> </form> </body> </html>