实现既能用username又能用email登陆那里 出问题了

来源:6-3 用户登录-2

qq_书山压力大EE_0

2018-09-07

settings.py中

AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
)

users/views.py中

from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic.base import View

from .models import UserProfile
from .forms import LoginForm


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

# 类继承的方法写视图
class LoginView(View):
    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            pass
        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": "用户名或密码错误"})

然后进行调试时
发现CustomBackend里面打的断点 触发不了, 并且就算用正确的username登陆, 也会失败。
如果在settings.py中把AUTHENTICATION_BACKENDS的配置注释掉, 用username登陆正常。
实在找不出错误所在,求解答

写回答

1回答

bobby

2018-09-10

你可以 https://git.imooc.com/Project/coding-78/src/master/MxOnlie 到这里下载一下我的源码 对比一下两者的区别 如果还是不行你通过qq群找到我给我发个qq消息我看看

0
7
2015061501
回复
qq_书山压力大EE_0
老哥 怎么解决的啊
2019-03-24
共7条回复

Python3.6+django+xadmin,打造在线教育平台

【毕设】Python 2.7到3.6 完美适配,Django升级2.0

3677 学习 · 4038 问题

查看课程