登录功能
模板页面
sign/templates/index.html
html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>发布会管理</h1>
<form action="/login/" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button id="btn" type="submit">登录</button>
{% csrf_token %}
</form>
</body>
</html>
备注:
CSRF verification failed. Request aborted.

表格需要加一个 {% csrf_token %} 的标签。csrf 全称是 Cross Site Request Forgery。这是 Django 提供的防止伪装提交请求的功能。POST 方法提交的表格,必须有此标签。

再次使用POST请求,可以看到客户端提交带有一个token值

登录视图
python
from django.http import HttpResponse, Http404
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,"index.html")
def login(request):
if request.method=='POST':
username=request.POST.get("username",'')
password=request.POST.get("password",'')
if username=='admin' and password=="admin123":
return HttpResponse("登录成功")
else:
return render(request,'index.html',context={'error':'username or password error!'})
向服务器提交请求时,服务器可以通过request获取用户提交值
如获取POST请求中提交的name为username的值
<input type="text" id="username" name="username" required><br><br>
request.POST["username"]
或者 request.POST.get('username','')
获取请求名称:request.method
这里用返回了一个字符串
return HttpResponse("登录成功")
事件管理
模板页面
sign/templatesevent_manage.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Manage Page</title>
</head>
<body>
<h1>嗨 {{user}} 欢迎</h1>
</body>
</html>
视图函数
python
from django.http import HttpResponse, Http404,HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,"index.html")
def login(request):
if request.method=='POST':
username=request.POST.get("username",'')
password=request.POST.get("password",'')
if username=='admin' and password=="admin123":
response=HttpResponseRedirect('/event_manage/')
response.set_cookie('user',username,3600)
return response
else:
return render(request,'index.html',context={'error':'username or password error!'})
def event_manage(request):
username=request.COOKIES.get('user','')
return render(request,'event_manage.html',{"user":username})
httpresponserediect为重定向,登录后页面被重定向至实践管理页面

这里采用response.set_cookie方法为客户端设置了cookie user=username
使用request.COOKIES.get()方法获取到客户端访问时带的cookie。
如果想给模板传值,需要在render第三个参数提供字典,字段名:值,
在模板中采用双引号{{字段名}}读取返回值。
也可以使用session
response.session["user"]=username

要用sesssion需要创建django自带的数据表session
控制台执行python manage.py migrate

重新登陆,可以看到设置的sessionid

使用django认证
创建一个admin用户,这里用的是django自带的管理员账号功能。

运行项目,访问http://127.0.0.1:8000/admin
使用创建的账号登录,并创建一个user

修改登录函数使用django的认证

输入正确账号密码可以登录,输出不存在账号密码登录失败。
设置视图仅登录后可用

设置装饰loginrequired后,直接访问视图会报错
