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回答
-
django 换回2.0比较稳定 这个地方建议debug看前端变量传递是否被正确接收 逐步调试下 Q(username=username) | Q(email=username) 而且像这种位置 没有必要加的空格就不要加 一些为止报错就是因为这些小细节
012019-04-28 -
Ethreal
2019-04-28
settings 是否配置
00
相似问题