django用户认证

Posted 人生苦短,我用python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django用户认证相关的知识,希望对你有一定的参考价值。

方法一、利用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

 

以上是关于django用户认证的主要内容,如果未能解决你的问题,请参考以下文章

django用户认证系统——登录4

Django用户认证

Django——用户认证

Django的用户认证----介绍

Django之用户认证Auth组件

Django 自定义用户认证