多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[success] # django自带的登录 * * * * * >[danger] ##### authenticate-验证用户名密码是否存在 **英文鉴定的意思,引入下面这个库** `from django.contrib.auth ` **使用方法:** ~~~ user = authenticate(username=username,password = pwd) 讲解: 接收用户名和密码,注意这里返回的是一个对象,如果不存在返回是None <class 'django.contrib.auth.models.User'> ~~~ * * * * * <br> >[danger] ##### login-验证用户名密码是否存在 `from django.contrib.auth import login` > login()使用Django的session框架来将用户的ID保存在session中。 **官方文档建议用法:** ~~~ from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... ~~~ * * * * * <br> >[danger] ##### logout-退出当前用户 **官方文档建议:** ~~~ from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page. ~~~ * * * * * <br> >[danger] ##### 代码解读 **注:** ``` 这里用了自带的验证装饰器。详细见-crm下的view from django.contrib.auth.decorators import login_required 讲解 ``` **讲解:** ``` 当用户没登录的时候,访问一些只有登录后才能访问的页面, 链接在上面说的装饰器的修改下,会在当前的登录页面后面加 ?next='访问的调回页面的网址' ``` **如图:** ![](https://box.kancloud.cn/9f211c9b5a2fb3d44bdaf461f71477f7_351x45.png) ``` 所以在request.GET.get('next',"/login/"),做了点文章,如果不存在next应该让页面重新调回原来的登录链接,如果登录成功了,页面会自动访问之前的访问失败页面 ``` ![](https://box.kancloud.cn/157d0f9c2dad6c7d9a4e4edca6b42f83_710x319.png) >[danger] ##### 完整代码 ~~~ from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout # Create your views here. def acc_login(request): erro = "" if request.method == "POST": username = request.POST.get('username') pwd = request.POST.get('password') user = authenticate(username=username,password = pwd) if user: login(request,user) # return redirect("/crm/") return redirect(request.GET.get('next',"/login/")) else: erro="用户名密码错误" return render(request,'login.html',{'erro':erro}) def acc_logout(request): logout(request) return redirect('/login/') ~~~