创建自定义验证用户名密码类CustomBackend
users/views.py
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.shortcuts import render
# Create your views here.
from users.models import UserProfile
class CustomBackend(ModelBackend): # 继承认证类,diy它
def authenticate(self, request, username=None, password=None, **kwargs):
try: # 验证用户名密码 否则返回None
user = UserProfile.objects.get(username=username) # 表示有这个用户 查处自定义usermodel的用户名,
if user.check_password(password): # 表示这个用户密码正确, 这里django存储密码是加密的,必须用其下这个方法加密后比对是否正确
return user
except Exception as e:
return None # 密码错误返回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) # django执行用户登录
return render(request, "index.html")
else:
return render(request, "index.html", {})
elif request.method == "GET":
return render(request, "login.html", {})
users/settings.py
AUTH_USER_MODEL = "users.UserProfile"
AUTHENTICATION_BACKENDS = (\'users.views.CustomBackend\',)
断点调试, 确实已经用了我们自定义的认证类.
允许用户名用邮箱登录
且的关系
user = UserProfile.objects.get(username=username,email=username)
或的关系: django自带了Q实现
from django.db.models import Q
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
users/views.py完整的
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class CustomBackend(ModelBackend): # 继承认证类,diy它
def authenticate(self, request, username=None, password=None, **kwargs):
try: # 验证用户名密码 否则返回None
user = UserProfile.objects.get(Q(username=username) | Q(email=username)) # 表示有这个用户 查处自定义usermodel的用户名,
if user.check_password(password): # 表示这个用户密码正确, 这里django存储密码是加密的,必须用其下这个方法加密后比对是否正确
return user
except Exception as e:
return None # 密码错误返回None
前端输错用户名密码错误提示
users/views.py
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) # django执行用户登录
return render(request, "index.html")
else:
return render(request, "login.html", {\'msg\':"用户名或密码错误"})
elif request.method == "GET":
return render(request, "login.html", {})
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<div>
<form action="/login/" method="post">
<p><input type="text" name="username" placeholder="username"></p>
<p><input type="text" name="password" placeholder="password"></p>
<p><input type="submit"></p>
{% csrf_token %}
</form>
{{ msg }}
</div>
</body>
</html>