用django 自带的判断用户登录

一、使用

使用的包文件
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
重写ModelBackend类里面的authenticate方法
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except:
            return None
登陆方法中使用+验证
def user_login(request):
    if request.method == "POST":
        user_name = request.POST.get('username')
        pass_word = request.POST.get('password')
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:
            login(request, user)
            return render(request, 'index.html')
        else:
            return render(request, 'login.html', {'msg': '密码错误'})

    elif request.method == "GET":
        return render(request, 'login.html', {})

你可能感兴趣的:(用django 自带的判断用户登录)