CBV及CBV登录验证

CBV实现登录验证

通过 CBV 继承的 View 源码,可以看到通过调用 as_view 中的 view 方法,最后返回的是对应类的 self.dispatch(request, *, **)

那么可以在调用 dispatch 之前做一个 session 验证,实现登录验证。
urls.py

1
2
3
4
5
6
7
8
from django.conf.urls import url
from django.contrib import admin
from demo01 import views

urlpatterns = [
url(r'^index_demo', views.Index.as_view()),
url(r'^login_demo', views.CBV.as_view()),
]

views.py

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
class Auth(View):
def dispatch(self, request, *args, **kwargs):
if request.session.get('login', False):
response = super(Auth, self).dispatch(request, *args, **kwargs)
return response
else:
return redirect('/login')


class Index(Auth):
def get(self, request):
return HttpResponse('Index')

class CBV(View):
def get(self, request):
# self.dispatch()
return render(request, 'login.html')

def post(self, request):
username = request.POST.get('username', False)
password = request.POST.get('password', False)
if not username or not password:
return HttpResponse('用户名密码不能为空')
else:
user_obj = models.UserInfo.objects.filter(username=username, password=password)

if user_obj.first(): # 登录成功
request.session['login'] = user_obj.first().name # 创建session
return redirect('/session')
else: # 登录失败
return HttpResponse('用户名密码错误')

templates/login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<div>
<form method="post">
用户名:<input type="text" name="username">
密码:<input type="text" name="password">
<input type="submit" value="提交">
</form>
</div>
</body>
</html>

Recommended Posts