1. settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', # 默认不注释,关闭注释
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2. 配置html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1> 欢迎来到网站首页!</h1>
{#<a href="/test01/index/"> test01 首页 </a>#}
{#<a href="/test02/index/"> test02 首页 </a>#}
<form action="/test01/login/" method="post" >
{% csrf_token %} {# 有了csrf_token 就会生成tocken验证 #}
user: <input type="text" name="username">
passwd: <input type="text" name="passwd">
<button>提交</button>
</form>
</body>
</html>
3. urls.py
path('login/', views.login),
4. views.py
def login(request):
method = request.method # 获取用户请求方式
if method == 'GET':
return render(request,'index.html')
else:
username = request.POST.get('username')
password = request.POST.get('passwd')
if username == 'guo' and password == 'guo':
return redirect('/test01/base/')
else:
return HttpResponse('登录失败')
5. 验证
自动生成了tocken值