逻辑: 首先返回一个登录页面, 认证登录的用户名密码,验证无误后设置cookie, 返回index页面 输入错误返回login重新验证登录。

视图逻辑配置

  1. from django.shortcuts import render,HttpResponse,redirect
  2. from django.views import View
  3. # Create your views here.
  4. def login_auth(func):
  5. def inner(request,*args,**kwargs):
  6. is_login = request.COOKIES.get('is_login')
  7. if is_login == "True":
  8. ret = func(request,*args,**kwargs)
  9. return ret
  10. else:
  11. return redirect('login')
  12. return inner
  13. class Loginview(View):
  14. '''
  15. 首先返回一个登录页面, 认证登录的用户名密码,验证无误后设置cookie, 返回index页面 输入错误返回login让重新登录
  16. '''
  17. def get(self,request):
  18. return render(request,'login.html')
  19. def post(self,request):
  20. user = request.POST.get('user')
  21. pwd = request.POST.get('pass')
  22. if user == 'guo' and pwd == 'guo':
  23. # 登录成功后设置 cookie
  24. ret = render(request,'index.html') # url别名跳转
  25. ret.set_cookie('is_login',True)
  26. return ret # 返回home页面
  27. else:
  28. return render(request,'login.html')
  29. @login_auth # 判断用户是否登录 判断cookie
  30. def home(request):
  31. '''
  32. 返回home页面
  33. '''
  34. # is_login = request.COOKIES.get('is_login')
  35. # if is_login == 'True':
  36. return render(request,'home.html')
  37. # else:
  38. # return render(request,'login.html')

url配置

  1. from django.contrib import admin
  2. from django.urls import path
  3. from test01 import views
  4. urlpatterns = [
  5. path('admin/', admin.site.urls),
  6. path('login/',views.Loginview.as_view(),name='login'),
  7. path('home/', views.home, name='home'),
  8. ]

Html配置

login.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Login</title>
  6. </head>
  7. <body>
  8. <h1> 登录 </h1>
  9. <form action="/login/" method="post">
  10. {% csrf_token %}
  11. 用户名<input type="text" name="user">
  12. 密码 <input type="text" name="pass">
  13. <button>提交</button>
  14. </form>
  15. </body>
  16. </html>

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Index</title>
  6. </head>
  7. <body>
  8. <h1> 这是首页!</h1>
  9. <a href="/home/">home目录</a>
  10. </body>
  11. </html>

home.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>home</title>
  6. </head>
  7. <body>
  8. <h1> 这里是home目录 </h1>
  9. </body>
  10. </html>