authenticate验证时user总是返回None

来源:6-4 用form实现登录-1

米兰的小铁匠_feng

2019-04-27

python版本3.7,django版本2.2

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


# Create your views here.
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):
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)
        print(user)
        if user is not None:
            login(request, user)
            return render(request, 'index.html')
        else:
            return render(request, "login.html", {"msg": "用户名或密码错误!"})
写回答

2回答

Ethreal

2019-04-28

django 换回2.0比较稳定  这个地方建议debug看前端变量传递是否被正确接收 逐步调试下  Q(username=username) | Q(email=username)  而且像这种位置 没有必要加的空格就不要加 一些为止报错就是因为这些小细节

0
1
米兰的小铁匠_feng
换成django2.0终于成功了! 谢谢!
2019-04-28
共1条回复

Ethreal

2019-04-28

//img.mukewang.com/szimg/5cc59582000129fd07820240.jpgsettings 是否配置

0
0

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

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

3677 学习 · 4038 问题

查看课程