逻辑: 首先返回一个登录页面, 认证登录的用户名密码,验证无误后设置cookie, 返回index页面 输入错误返回login重新验证登录。
视图逻辑配置
from django.shortcuts import render,HttpResponse,redirect
from django.views import View
# Create your views here.
def login_auth(func):
def inner(request,*args,**kwargs):
is_login = request.COOKIES.get('is_login')
if is_login == "True":
ret = func(request,*args,**kwargs)
return ret
else:
return redirect('login')
return inner
class Loginview(View):
'''
首先返回一个登录页面, 认证登录的用户名密码,验证无误后设置cookie, 返回index页面 输入错误返回login让重新登录
'''
def get(self,request):
return render(request,'login.html')
def post(self,request):
user = request.POST.get('user')
pwd = request.POST.get('pass')
if user == 'guo' and pwd == 'guo':
# 登录成功后设置 cookie
ret = render(request,'index.html') # url别名跳转
ret.set_cookie('is_login',True)
return ret # 返回home页面
else:
return render(request,'login.html')
@login_auth # 判断用户是否登录 判断cookie
def home(request):
'''
返回home页面
'''
# is_login = request.COOKIES.get('is_login')
# if is_login == 'True':
return render(request,'home.html')
# else:
# return render(request,'login.html')
url配置
from django.contrib import admin
from django.urls import path
from test01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',views.Loginview.as_view(),name='login'),
path('home/', views.home, name='home'),
]
Html配置
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1> 登录 </h1>
<form action="/login/" method="post">
{% csrf_token %}
用户名<input type="text" name="user">
密码 <input type="text" name="pass">
<button>提交</button>
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1> 这是首页!</h1>
<a href="/home/">home目录</a>
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>home</title>
</head>
<body>
<h1> 这里是home目录 </h1>
</body>
</html>