Django的登录模块
Django的登录模块
导入
from django.contrib.auth.decorators import login_required #登录验证装饰器
from django.contrib.auth.models import User
from django.contrib import auth #登录 改密 注销一些的相关操作
装饰器
@login_required(login_url='/login/') #装饰器 如果未登录 直接跳转 /login/
def index(request):
return render(request, "index.html", {'msg': '又是美好的一天'})
注册
def register(request):
if request.method == 'GET':
return render(request, 'register.html')
else:
username = request.POST.get('username') #获取前端传来的帐号和密码
pwd = request.POST.get('pwd')
# User.objects.create_superuser(username=username, password=pwd, email='111@qq.com')
User.objects.create_user(username=username, password=pwd) #创建一个用户
return HttpResponse('ok')
修改密码
@login_required(login_url='/login/') #因为是登录之后才能改密码,所以需要登录之后改密码
def modify(request):
if request.method == 'GET':
return render(request, 'modify.html')
else:
old_pwd = request.POST.get('oldpwd')
new_pwd = request.POST.get('newpwd')
res = request.user.check_password(old_pwd) #检测老密码的加密结果
if res:
request.user.set_password(new_pwd) #设置新的密码
request.user.save() #一定记得保存
return HttpResponse('ok')
else:
return render(request, 'modify.html')
登录
def login(request):
if request.method == 'GET':
return render(request, 'login.html', {'meiri': 'xixi'})
else:
# 获取用户名和密码
username = request.POST.get('username')
pwd = request.POST.get('pwd')
print(username, pwd)
myuser = auth.authenticate(request, username=username, password=pwd) #登录帐号 成功返回帐号,失败返回None
if myuser is not None:
my = auth.login(request, myuser)
return render(request, 'index.html')
else:
return render(request, "login.html", {'res': '登录失败!'})
个性签名:独学而无友,则孤陋而寡闻!
如果觉得这篇文章对你有小小的帮助的话,记得点个“关注”哦,博主在此感谢!还可以扫码添加好友,交流编程上的问题哦!
万水千山总是情,点赞再走行不行!哈哈哈(っ•̀ω•́)っ✎⁾⁾!