django权限控制功能实现

本文介绍了如何在Django框架中实现权限控制功能。通过创建中间件middleware.py,实现用户登录检查,详细讲述了在views.py中编写登录注销函数,并在settings.py中启用中间件的配置步骤。
摘要由CSDN通过智能技术生成

django框架自带用户权限功能,在django.contrib.auth模块下,使用时需要导入该模块。

1、在app下创建一个中间件middleware.py文件,用户拦截并判断用户是否登录,内容如下:

class UserAuthModdleware(object):
    def process_request(self, request):
        path = request.path
        if path == '/userLogin/' or path == '/check_code/' :#不拦截
            return None
        elif not request.user.is_authenticated():#验证不通过进入登录界面
            return render(request,'login.html')
        return None

2、在views.py中写用户登录注销函数

from django.contrib.auth import authenticate,login,logout
#用户登录
def userLogin(request):
    try:
        if request.method == 'POST':
            req = request.POST.copy()
            username = req.get('username')
            password = req.get('password')
            checkCode = req.get('check_code')

            if checkCode.upper() == request.session['checkCode'].upper():
                if username != None and password != None:
                   #authenticate是django.contrib.auth中验证函数
                    **newUser = authenticate(username=username, password=password)**
                    if newUser:
                        login(request, newUser)
                        request.session.set_expiry(30 * 60)
                        return HttpRes
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值