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
|
一、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
属性
|
本文转自小白的希望 51CTO博客,原文链接:http://blog.51cto.com/haoyonghui/1964501,如需转载请自行联系原作者