一.最完美的auth
auth_user 是用来存储的用户注册的username,password
auth 首先需要引入模块
from django.contrib import auth 用户认证的前提是:使用django自带用户表auth_user 插入数据,在manage.py下插入 createsuperuser 通过添加username,password 来实现创建auth_user 登录数据表 1.登录逻辑
1 def login(request): 2 3 if request.method == "GET": 4 return render(request, "login.html") 5 else: 6 #1.接收输入用户名和密码 7 user = request.POST.get("user") 8 pwd = request.POST.get("pwd") 9 print(user, pwd)10 #2. 通过auth.authenticate判断输入的是否正确11 #这里有三次变化{ 12 # 1.将用户名,密码输入在user_name进行验证,成功后生成系统自带的随机session_id13 # 2.将输入的用户名和密码写入14 # 3.给浏览器返回session_id15 #}16 17 user_obj = auth.authenticate(username=user, password=pwd)18 #4,如果输入成功,返回登录页面19 if user_obj:20 #5.将user_obj赋值给user21 auth.login(request, user_obj)22 return redirect("/books/")23 else:24 return redirect("/login/")
2.注销,本质上是flush()操作,清楚session_id
1 def logout(request):2 auth.logout(request)3 return redirect("/login/")
3.注册
1 from django.contrib.auth.models import User 2 #1.注册前需要引入模块 3 4 def reg(request): 5 if request.method == "GET": 6 return render(request, "reg.html") 7 else: 8 user = request.POST.get("user") 9 pwd = request.POST.get("pwd")10 #2.User的为什么不用create,因为用create会生成明文,不安全11 #这个创建在user_auth里12 User.objects.create_user(username=user, password=pwd)13 return redirect("/books/")
4.修改密码
1 def set_password(request): 2 if request.method == "GET": 3 return render(request, "set_password.html") 4 else: 5 #1.验证用户名是否存在 6 user = User.objects.get(username=request.user.username) 7 pwd = request.POST.get("pwd") 8 #2修改密码 9 user.set_password(raw_password=pwd)10 user.save()11 return redirect("/books/")