一.建立Form類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
|
#!/usr/bin/env python
from django.forms import Form
from django.forms import widgets
from django.forms import fields
class MyForm(Form):
user = fields.CharField(
widget=widgets.TextInput(attrs={"id": "i1", "class": "c1"}), # 定製html標籤
label="用戶名"
)
gender = fields.ChoiceField(
choices=((1, "男"), (2, "女")),
initial=2, # 設置默認值
widget=widgets.RadioSelect,
label="性別"
)
city = fields.CharField(
initial=2,
widget=widgets.Select(choices=((1,"上海"), (2,"北京"), (3,"重慶"))),
label="城市"
)
pwd = fields.CharField(
widget=widgets.PasswordInput(attrs={"class":"p1"}, render_value=True),
label="性別"
)
|
2.view函數處理前端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
from django.shortcuts import render, redirect
# Create your views here.
from day60app.form_cls import MyForm
def index(request):
if request.method == "GET":
obj = MyForm()
return render(request, "index.html", {"obj": obj})
elif request.method == "POST":
obj = MyForm(request.POST, request.FILES)
if obj.is_valid():
v = obj.cleaned_data
print("用戶驗證成功信息", v)
return redirect("http://www.jd.com")
else:
v = obj.errors
print("錯誤信息", v)
return render(request, "index.html", {"obj": obj})
|
3,生成html標籤python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!
DOCTYPE
html>
<
html
lang="en">
<
head
>
<
meta
charset="UTF-8">
<
title
>Title</
title
>
</
head
>
<
body
>
<
h1
>Hello World</
h1
>
<
form
action="/index/" method="post" enctype="multipart/form-data" novalidate>
<
p
>{{ obj.user.label }}{{ obj.user }}{{ obj.user.errors.0 }}</
p
>
<
p
>{{ obj.gender.label }}{{ obj.gender }}{{ obj.gender.errors.0 }}</
p
>
<
p
>{{ obj.pwd.label }}{{ obj.pwd }}{{ obj.pwd.errors.0 }}</
p
>
<
p
>{{ obj.city.label }}{{ obj.city }}{{ obj.city.errors.0 }}</
p
>
<
input
type="submit" value="提交">
</
form
>
</
body
>
|
建立Form類時,主要涉及到 【字段】 和 【插件】,字段用於對用戶請求數據的驗證,插件用於自動生成HTML;git
一、Django內置字段以下:正則表達式
1
2
3
4
5
6
7
8
9
10
11
12
|
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內容後綴
|
示例:數據庫
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class TestForm(forms.Form):
user = fields.CharField(
required=True,
max_length=12,
min_length=3,
error_messages={},
widget = widgets.TextInput(attrs={"class":123}), # 定製html插件,屬性:用attrs參數
# widget= widgets.Textarea()
label="姓名",
initial='laiying',
show_hidden_initial=False,
# validators=[] #自定製驗證規則
# disabled=True
label_suffix=":"
)
|
Django內置字段以下:django
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
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類型
|
需求: 在頁面上不用加self直接顯示input框app
效果:dom
代碼以下:函數
text.html
<body>
{{txt}}
</body>
views.py
1
2
3
4
5
6
|
def test(request):
if request.methon == 'GET':
txt = "<
input
type='text' />"
from django.utils.safestring import mark_safe
txt = mark_safe(txt)
return render(request,'text.html',{'txt':txt})
|
注:UUID是根據MAC以及當前時間等建立的不重複的隨機字符串
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
|
>>> 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內置插件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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
|
經常使用選擇插件
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
|
<
strong
># 單radio,值爲字符串</
strong
>
# user = fields.CharField(
# initial=2,
# widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
# )
<
strong
># 單radio,值爲字符串</
strong
>
# user = fields.ChoiceField(
# choices=((1, '上海'), (2, '北京'),),
# initial=2,
# widget=widgets.RadioSelect
# )
<
strong
># 單select,值爲字符串</
strong
>
# user = fields.CharField(
# initial=2,
# widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
# )
<
strong
># 單select,值爲字符串</
strong
>
# user = fields.ChoiceField(
# choices=((1, '上海'), (2, '北京'),),
# initial=2,
# widget=widgets.Select
# )
<
strong
># 多選select,值爲列表</
strong
>
# user = fields.MultipleChoiceField(
# choices=((1,'上海'),(2,'北京'),),
# initial=[1,],
# widget=widgets.SelectMultiple
# )
<
strong
># 單checkbox</
strong
>
# user = fields.CharField(
# widget=widgets.CheckboxInput()
# )
<
strong
># 多選checkbox,值爲列表</
strong
>
# user = fields.MultipleChoiceField(
# initial=[2, ],
# choices=((1, '上海'), (2, '北京'),),
# widget=widgets.CheckboxSelectMultiple
# )
|
示例:
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
|
#select框的兩種寫法 #方法一: # xdb = fields.CharField(
# widget=widgets.Select(choices=[(1,'剛娘'),(2,'鐵娘'),(3,'鋼彈')])
# )
#方法二:
# xdb = fields.IntegerField(
# widget=widgets.Select(choices=[(1,'剛娘'),(2,'鐵娘'),(3,'鋼彈')])
# )
# xdb = fields.ChoiceField(
# choices=[(1,'剛娘'),(2,'鐵娘'),(3,'鋼彈')]
# )
#多選下拉框(有自定義屬性)
# xdb = fields.MultipleChoiceField(
# choices=[(1, '剛娘'), (2, '鐵娘'), (3, '鋼彈')],
# widget=widgets.SelectMultiple(attrs={'class':'c1'}) #後面參數是定製屬性
# )
#單選checkbox
# xdb = fields.CharField(
# widget=widgets.CheckboxInput()
# )
#多選checkbox (多個checkbox,二選一)
# xdb = fields.MultipleChoiceField(
# initial=[2, ],
# choices=((1, '上海'), (2, '北京'),),
# widget=widgets.CheckboxSelectMultiple
# )
#多個選項Radio (互斥 三選一)
# xdb = fields.ChoiceField(
# choices=((1, '上海'), (2, '北京'),(3, '北京1'),),
# initial=2,
# widget=widgets.RadioSelect
# )
|
在使用選擇標籤時,須要注意Choices 的選項能夠從數據庫中獲取,可是因爲是靜態字段***獲取的值沒法實時更新***,那麼須要自定義構造方法從而達到此目的。
方法一:(推薦使用)
models.py
1
2
3
4
5
|
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField(max_length=32)
|
urls.py
1
2
3
4
5
6
7
|
from django.conf.urls import url
from django.contrib import admin
from app02 import views as v2
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^love/', v2.love),
]
|
views.py
1
2
3
4
5
6
7
8
9
10
11
12
|
from app01 import models
class LoveForm(forms.Form):
price = fields.IntegerField()
user_id = fields.IntegerField(
# widget=widgets.Select(choices=[(0,'alex'),(1,'劉皓宸'),(2,'楊建'),])
widget=widgets.Select()
)
#自定義構造方法,實時刷新頁面數據
def __init__(self, *args, **kwargs):
super(LoveForm, self).__init__(*args, **kwargs)
self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id', 'username')
|
test.html
1
2
3
4
5
6
7
8
9
10
11
12
|
<!
DOCTYPE
html>
<
html
lang="en">
<
head
>
<
meta
charset="UTF-8">
<
title
>Title</
title
>
</
head
>
<
body
>
<
h1
>有緣千里來相會</
h1
>
<
p
>價格:{{ obj.price }}</
p
>
<
p
>姑娘:{{ obj.user_id }}</
p
>
</
body
>
</
html
>
|
方法二:(不推薦使用)
使用django提供的ModelChoiceField和ModelMultipChoiceField字段來實現
(這種django內置的方法不推薦使用,若是要在前端顯示數據庫中的用戶名,須要依賴models中的__str__方法,並且一個class中只有一個__str__, 若是在有的場景中須要同時顯示如id user, age等多個字段名時,這個方法就作不到)
urls.py
1
2
3
4
5
6
7
|
from django.conf.urls import url
from django.contrib import admin
from app02 import views as v2
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^love/', v2.love),
]
|
test.html
1
2
3
4
5
6
7
8
9
10
11
12
|
<!
DOCTYPE
html>
<
html
lang="en">
<
head
>
<
meta
charset="UTF-8">
<
title
>Title</
title
>
</
head
>
<
body
>
<
h1
>有緣千里來相會</
h1
>
<
p
>價格:{{ obj.price }}</
p
>
<
p
>姑娘:{{ obj.user_id2 }}</
p
>
</
body
>
</
html
>
|
views.py
1
2
3
4
5
6
7
8
9
|
from django.forms.models import ModelChoiceField
class LoveForm(forms.Form):
price = fields.IntegerField()
user_id2 = ModelChoiceField(
queryset=models.UserInfo.objects.all(),
to_field_name='id'
)
|
models.py
1
2
3
4
5
6
7
8
9
10
|
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField(max_length=32)
def __str__(self):
return self.username
# 注意:依賴models中的str方法
|