在Django项目中同时允许电子邮件和用户名登录 [英] Allowing both email and username login in django project
问题描述
我正在为学校创建django项目,用户主要有三种:父母,老师和学生。对于父母和老师,我希望他们使用电子邮件登录(他们目前在旧系统中使用电子邮件登录)。
I'm creating a django project for a school, and there are three main kinds of users - parents, teachers, and students. For parents and teachers, I would like them to login using email (they are currently using email logins for a legacy system).
但是,对于学生,我希望他们使用传统的用户名方法登录(因为年幼的孩子没有电子邮件)。可以在Django中做到吗?还是只允许一种用户身份验证模型?
However, for students, I would like them to login using the conventional username approach (since young kids don't have emails). Is this possible to do in Django or is there only one User Authentication model allowed?
推荐答案
您可以创建单独的 AuthenticationEmailBackend
仅用于通过电子邮件记录,并将其添加到设置中的 AUTHENTICATION_BACKENDS
中。这样,如果以前的 AUTHENTICATION_BACKENDS
验证失败,则使用不同的 AUTHENTICATION_BACKENDS
作为替代。
You can create separate AuthenticationEmailBackend
just for logging by email and add it to AUTHENTICATION_BACKENDS
in settings. In this way different AUTHENTICATION_BACKENDS
are used as alternatives if authentication fails for previous AUTHENTICATION_BACKENDS
.
app / auth.py
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
class AuthenticationEmailBackend(object):
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if getattr(user, 'is_active', False) and user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
settings.py
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
...
"app.auth.AuthenticationEmailBackend",
)
如果保留默认值 django.contrib。列表中的auth.backends.ModelBackend
用户可以通过用户名或电子邮件登录。
If you leave default django.contrib.auth.backends.ModelBackend
in a list users can login by either username or email.
这篇关于在Django项目中同时允许电子邮件和用户名登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!