1. settings.py

  1. MIDDLEWARE = [
  2. 'django.middleware.security.SecurityMiddleware',
  3. 'django.contrib.sessions.middleware.SessionMiddleware',
  4. 'django.middleware.common.CommonMiddleware',
  5. 'django.middleware.csrf.CsrfViewMiddleware', # 默认不注释,关闭注释
  6. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  7. 'django.contrib.messages.middleware.MessageMiddleware',
  8. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  9. ]

2. 配置html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>首页</title>
  6. </head>
  7. <body>
  8. <h1> 欢迎来到网站首页!</h1>
  9. {#<a href="/test01/index/"> test01 首页 </a>#}
  10. {#<a href="/test02/index/"> test02 首页 </a>#}
  11. <form action="/test01/login/" method="post" >
  12. {% csrf_token %} {# 有了csrf_token 就会生成tocken验证 #}
  13. user: <input type="text" name="username">
  14. passwd: <input type="text" name="passwd">
  15. <button>提交</button>
  16. </form>
  17. </body>
  18. </html>

3. urls.py

  1. path('login/', views.login),

4. views.py

  1. def login(request):
  2. method = request.method # 获取用户请求方式
  3. if method == 'GET':
  4. return render(request,'index.html')
  5. else:
  6. username = request.POST.get('username')
  7. password = request.POST.get('passwd')
  8. if username == 'guo' and password == 'guo':
  9. return redirect('/test01/base/')
  10. else:
  11. return HttpResponse('登录失败')

5. 验证

自动生成了tocken值
image.png