方法一、利用django自带的认证方式
登录视图函数
from django.views import View from django.shortcuts import render,redirect,HttpResponse from django.contrib.auth import login,logout,authenticate class LoginView(View): def post(self,request,*args,**kwargs): err_msg = {} username = request.POST.get(‘username‘) password = request.POST.get(‘password‘) user = authenticate(username=username, password=username)#认证用户 if user: login(request,user)#通过认证注册,cookie+session return redirect(request.GET.get(‘next‘) if request.GET.get(‘next‘) else "/index.html")#跳转到首页或者next.html else: err_msg[‘error‘] = ‘用户名密码错误!‘ return render(request, ‘login.html‘,{‘error‘:err_msg})
def get(self,request,*args,**kwargs):
return render(request,‘login.html‘)
注销视图函数
from django.views import View from django.contrib.auth import login,logout,authenticate class LogoutView(View): def get(self,request,*args,**kwargs): logout(request) return redirect(‘/login/‘)
认证使用
login_required装饰器
在需要认证的类上加上装饰器即可,CBV需要用method_decorator
from django.views import View from django.shortcuts import render,HttpResponse,redirect from django.contrib.auth.decorators import login_required #认证用户是否登录 @method_decorator(login_required,name=‘dispatch‘) class AssetListView(View): def get(self, request, *args, **kwargs): return render(request, ‘asset_list.html‘)
方式二、通过cookie或者session自己写认证
1.装饰器函数
def login_auth(func): ‘‘‘ 用户登录认证 :param func: :return: ‘‘‘ def inner(request,*args,**kwargs): v = request.COOKIES.get(‘current_user‘) if not v: url = ‘login/‘ + ‘?next=‘ + request.path return redirect(url) return func(request,*args,**kwargs) return inner
2.views.py
判断用户名密码是否正确,正确就set cookie
class LoginView(View): def post(self,request,*args,**kwargs): err_msg = {} username = request.POST.get(‘username‘) password = request.POST.get(‘password‘) user_obj = models.UserProfile.objects.filter(name=username,pwd=password).first() if user_obj: res = redirect(request.GET.get(‘next‘) if request.GET.get(‘next‘) else "/asset.html") res.set_cookie(‘current_user‘, username) return res else: err_msg[‘error‘] = ‘用户名密码错误!‘ return render(request, ‘login.html‘,{‘error‘:err_msg}) def get(self,request,*args,**kwargs): return render(request,‘login.html‘)
注销时清cookie
from django.views import View from django.shortcuts import render,redirect,HttpResponse class LogoutView(View): def get(self,request,*args,**kwargs): res = redirect(‘/login/‘) res.delete_cookie(‘current_user‘) return res