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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
|
一、FBV和CBV
FBV:是视图函数以函数的方式写逻辑代码
CBV:是视图以类的方式写逻辑代码
如CBV: views.py
from
django.shortcuts
import
render,HttpResponse,redirect
from
django.views
import
View
from
django.views.decorators.csrf
import
csrf_exempt,csrf_protect
from
django.utils.decorators
import
method_decorator
from
app01
import
models
class
LoginView(View):
@method_decorator(csrf_exempt)
def
dispatch(
self
, request,
*
args,
*
*
kwargs):
return
super
(LoginView,
self
).dispatch(request,
*
args,
*
*
kwargs)
def
get(
self
, request,
*
args,
*
*
kwargs):
return
render(request,
'login.html'
)
def
post(
self
,request,
*
args,
*
*
kwargs):
user
=
request.POST.get(
'user'
)
pwd
=
request.POST.get(
'pwd'
)
obj
=
models.UserInfo.objects.
filter
(username
=
user,password
=
pwd).first()
if
obj:
request.session[
'user_info'
]
=
{
'id'
: obj.
id
,
'username'
: obj.username}
return
redirect(
'/users.html'
)
return
render(request,
'login.html'
, {
'msg'
:
'去你的'
})
如FBV: views.py
def
register(request):
if
request.method
=
=
"GET"
:
form
=
RegisterForm()
return
render(request,
'register.html'
, {
'form'
: form})
else
:
response
=
{
'status'
:
True
,
'data'
:
None
,
'msg'
:
None
}
form
=
RegisterForm(request.POST)
if
form.is_valid():
print
(form.cleaned_data)
else
:
response[
'status'
]
=
False
response[
'msg'
]
=
form.errors
return
HttpResponse(json.dumps(response))
二、form表单组建使用
导入forms模块
from
django.forms
import
Form
from
django.forms
import
fields
from
django.forms
import
widgets
#创建表单类
class
UserForm(Form):
username
=
fields.CharField(
required
=
True
,
error_messages
=
{
'required'
:
'用户名不能为空'
},
widget
=
widgets.TextInput(attrs
=
{
'class'
:
'form-control'
})
)
password
=
fields.CharField(
required
=
True
,
error_messages
=
{
'required'
:
'邮箱不能为空'
,
'invalid'
:
'邮箱格式错误'
},
widget
=
widgets.TextInput(attrs
=
{
'class'
:
'form-control'
})
)
ut_id
=
fields.ChoiceField(
choices
=
[],
widget
=
widgets.Select(attrs
=
{
'class'
:
'form-control'
})
)
role_id
=
fields.MultipleChoiceField(
choices
=
[],
widget
=
widgets.SelectMultiple(attrs
=
{
'class'
:
'form-control'
})
)
def
__init__(
self
,
*
args,
*
*
kwargs):
super
(UserForm,
self
).__init__(
*
args,
*
*
kwargs)
self
.fields[
'ut_id'
].choices
=
models.UserType.objects.values_list(
'id'
,
'title'
)
self
.fields[
'role_id'
].choices
=
models.Role.objects.values_list(
'id'
,
'caption'
)
注: username, password,渲染到页面是
input
标签属性的name值
fields.CharField表示输入文本类型,
fields.ChoiceField表示单选下拉框
fields.MultipleChoiceField表示多选下拉框
required
=
True
表示必填选项
error_messages
=
{
'required'
:
'用户名不能为空'
}表示错误提示
widget
=
widgets.TextInput(attrs
=
{
'class'
:
'form-control'
})表示增加
class
属性
form表单对页面渲染
views.py
class
AddUserView(AuthView, View):
def
get(
self
, request,
*
args,
*
*
kwargs):
form
=
UserForm()
return
render(request,
'add_user.html'
, {
'form'
: form})
def
post(
self
,request,
*
args,
*
*
kwargs):
form
=
UserForm(data
=
request.POST)
if
form.is_valid():
role_id_list
=
form.cleaned_data.pop(
'role_id'
)
obj
=
models.UserInfo.objects.create(
*
*
form.cleaned_data)
obj.rl.add(
*
role_id_list)
return
redirect(
'/users.html'
)
else
:
print
(form.errors)
return
render(request,
'add_user.html'
, {
'form'
: form})
add_user.html
<!DOCTYPE html>
<html lang
=
"en"
>
<head>
<meta charset
=
"UTF-8"
>
<title>Title<
/
title>
<
/
head>
<body>
<h1>添加用户<
/
h1>
<form method
=
"POST"
novalidate>
{
%
csrf_token
%
}
<p>
用户名: {{ form.username }} {{ form.errors.username.
0
}}
<
/
p>
<p>
密码: {{ form.password }} {{ form.errors.password.
0
}}
<
/
p>
<p>
用户类型: {{ form.ut_id }} {{ form.errors.ut_id.
0
}}
<
/
p>
<p>
角色: {{ form.role_id }} {{ form.errors.role_id.
0
}}
<
/
p>
<
input
type
=
"submit"
value
=
"提交"
>
<
/
form>
<
/
body>
<
/
html>
注: form.username表示name
=
"username"
的
input
框, form.errors.username.
0
验证填写是否正确,
错误返回error_messages
=
{
'required'
:
'用户名不能为空'
}编写的信息
三、登录验证:
继承:
单继承:
# class BaseView(View):
# def dispatch(self, request, *args, **kwargs):
# if request.session.get('username'):
# response = super(BaseView,self).dispatch(request, *args, **kwargs)
# return response
# else:
# return redirect('/login.html')
#
# class IndexView(BaseView):
#
# def get(self,request,*args,**kwargs):
return
HttpResponse(request.session[
'username'
])
多继承:
# 多继承方式:
# class BaseView(object):
# def dispatch(self, request, *args, **kwargs):
# if request.session.get('username'):
# response = super(BaseView,self).dispatch(request, *args, **kwargs)
# return response
# else:
# return redirect('/login.html')
#
# class IndexView(BaseView,View):
#
# def get(self,request,*args,**kwargs):
# return HttpResponse(request.session['username'])
装饰器:
def
auth(func):
def
inner(request,
*
args,
*
*
kwargs):
if
request.session.get(
'username'
):
obj
=
func(request,
*
args,
*
*
kwargs)
return
obj
else
:
return
redirect(
'/login.html'
)
return
inner
# @method_decorator(auth,name='get')
class
IndexView(View):
@method_decorator(auth)
def
dispatch(
self
, request,
*
args,
*
*
kwargs):
if
request.session.get(
'username'
):
response
=
super
(IndexView,
self
).dispatch(request,
*
args,
*
*
kwargs)
return
response
else
:
return
redirect(
'/login.html'
)
@method_decorator(auth)
def
get(
self
,request,
*
args,
*
*
kwargs):
return
HttpResponse(request.session[
'username'
])
@method_decorator(csrf_exempt)
# 无效
def
post(
self
,request,
*
args,
*
*
kwargs):
return
HttpResponse(request.session[
'username'
])
四、序列化
方式一:
user_list
=
models.UserInfo.objects.
all
()
data
=
serializers.serialize(
"json"
, user_list)
[
{
"model"
:
"app01.userinfo"
,
"pk"
:
1
,
"fields"
: {
"username"
:
"\u5174\u666e"
,
"password"
:
"123123"
}},
{
"model"
:
"app01.userinfo"
,
"pk"
:
2
,
"fields"
: {
"username"
:
"\u94f6\u79cb\u826f"
,
"password"
:
"666"
}}
]
方式二:
user_list
=
models.UserInfo.objects.values(
'id'
,
'username'
)
user_list
=
list
(user_list)
data
=
json.dumps(user_list)
[
{
"username"
:
"\u5174\u666e"
,
"id"
:
1
},
{
"username"
:
"\u94f6\u79cb\u826f"
,
"id"
:
2
}
问题:对json.dumps做定制:
import
json
from
datetime
import
date
from
datetime
import
datetime
class
JsonCustomEncoder(json.JSONEncoder):
def
default(
self
, field):
if
isinstance
(field, datetime):
return
field.strftime(
'%Y-%m-%d %H:%M:%S'
)
elif
isinstance
(field, date):
return
field.strftime(
'%Y-%m-%d'
)
else
:
return
json.JSONEncoder.default(
self
, field)
user_list
=
[
{
'id'
:
1
,
'name'
:
'alex'
,
'ctime'
: datetime.now()},
{
'id'
:
2
,
'name'
:
'eric'
,
'ctime'
: datetime.now()}
]
data
=
json.dumps(user_list,
cls
=
JsonCustomEncoder)
print
(data)
五、form表单验证总结
1
、创建Form类(本质就是正则表达式的集合)
from
django.forms
import
Form
from
django.forms
import
fields
from
django.forms
import
widgets
class
UserForm(Form):
username
=
fields.CharField(
required
=
True
,
error_messages
=
{
'required'
:
'用户名不能为空'
},
widget
=
widgets.TextInput(attrs
=
{
'class'
:
'form-control'
})
)
password
=
fields.CharField(
required
=
True
,
error_messages
=
{
'required'
:
'邮箱不能为空'
,
'invalid'
:
'邮箱格式错误'
},
widget
=
widgets.TextInput(attrs
=
{
'class'
:
'form-control'
})
ut_id
=
fields.ChoiceField(
choices
=
[],
widget
=
widgets.Select(attrs
=
{
'class'
:
'form-control'
})
)
role_id
=
fields.MultipleChoiceField(
choices
=
[],
widget
=
widgets.SelectMultiple(attrs
=
{
'class'
:
'form-control'
})
)
def
__init__(
self
,
*
args,
*
*
kwargs):
super
(UserForm,
self
).__init__(
*
args,
*
*
kwargs)
# self.fields已经有所有拷贝的字段
self
.fields[
'ut_id'
].choices
=
models.UserType.objects.values_list(
'id'
,
'title'
)
self
.fields[
'role_id'
].choices
=
models.Role.objects.values_list(
'id'
,
'caption'
)
2.
只是生成HTML标签: 添加页面
form
=
MyForm()
`form`.`xx`
3.
带默认值的HTML标签: 编辑页面
form
=
MyForm(initial
=
{
'xx'
: xxx})
`form`.`xx`
4.
提交数据
form
=
MyForm(data
=
request.POST)
if
form.is_valid():
print
(form.cleaned_data)
else
:
print
(form.errors)
问题:下拉框数据无法实时更新
class
UserForm(Form):
username
=
fields.CharField(
required
=
True
,
error_messages
=
{
'required'
:
'用户名不能为空'
}
)
password
=
fields.CharField(
required
=
True
,
error_messages
=
{
'required'
:
'邮箱不能为空'
,
'invalid'
:
'邮箱格式错误'
}
)
ut_id
=
fields.ChoiceField(choices
=
[])
def
__init__(
self
,
*
args,
*
*
kwargs):
super
(UserForm,
self
).__init__(
*
args,
*
*
kwargs)
self
.fields[
'ut_id'
].choices
=
models.UserType.objects.values_list(
'id'
,
'title'
)
|
本文转自小白的希望 51CTO博客,原文链接:http://blog.51cto.com/haoyonghui/1964492,如需转载请自行联系原作者