基础应用
1 from django.shortcuts import render, redirect 2 from django.contrib.auth import authenticate, login, logout #登入和登出 3 from django.contrib.auth.decorators import login_required # 验证用户是否登录 4 def acc_login(request): 5 if request.method == "POST": 6 username = request.POST.get("username") 7 password = request.POST.get("password") 8 9 user = authenticate(username=username,password=password) # 类型为<class 'django.contrib.auth.models.User'> 10 11 if user: 12 login(request,user) # 验证成功之后登录 13 return redirect('/api/index/') 14 15 return render(request, "login.html") 16 17 @login_required # 加上这个装饰器就是限制必须登录才能执行这个函数 18 def dashboard(request): 19 print(request.user) 20 return render(request, "index.html") 21 22 def acc_logout(request): 23 logout(request) # 登出 24 return redirect("/login")
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>欢迎登陆</h1> 9 <form action="/api/login/" method="post" novalidate> 10 {% csrf_token %} 11 <input type="text" name="username"> 12 <input type="password" name="password"> 13 <input type="submit" value="提交"> 14 </form> 15 </body> 16 </html>
升级版
django里面的自动登陆验证是和admin里面的用户信息进行验证的,想用来验证自己写的models,要改造源码
1 继承from django.contrib.auth.backends import ModelBackend,自定义验证
2 setting文件中设置一下验证引擎