您可以通过实现自己的用户模型然后告诉 django 如何验证用户来做到这一点。您的模型应如下所示:
class Users(models.Model):
id = models.IntegerField(primary_key=True)
is_active = models.IntegerField(default=1)
date_joined = models.DateTimeField(default=timezone.now)
last_login = models.DateTimeField(default=timezone.now)
username = models.CharField(max_length=30, unique=True)
password = models.CharField(max_length=30)
@property
def is_authenticated(self):
return True
您可以添加额外的字段,但 django 需要这些字段。属性 is_authenticated 应始终返回 true,如文档中所定义。
下一步是定义您的登录身份验证方式。在项目的任何地方创建一个文件名 backends.py,并在其中声明两个方法:authenticate 和 get_user,它应该是这样的:
from django.contrib.auth.backends import ModelBackend
from users.models import Users
from django.contrib.auth.hashers import *
from login.util import *
class PersonalizedLoginBackend(ModelBackend):
def authenticate(self, request=None, username=None, password=None, **kwars):
#Here define you login criteria, like encrypting the password and then
#Checking it matches. This is an example:
try:
user = Users.objects.get(username=username)
except Users.DoesNotExist:
return None
if check_password(password, user.password):
return user
else:
return None
def get_user(self, user_id):
#This shall return the user given the id
from django.contrib.auth.models import AnonymousUser
try:
user = Users.objects.get(id=user_id)
except Exception as e:
user = AnonymousUser()
return user
现在您需要在 settings.py 中告诉 django 后端位于何处:
AUTHENTICATION_BACKENDS = (
# ... your other backends
'path.to.backends.PersonalizedLoginBackend',
)
从那里您应该能够像平常一样登录,首先进行身份验证,然后使用 do_login 功能。
在此处阅读更多详细信息:
https://docs.djangoproject.com/en/2.2/topics/auth/customizing/