django 使用手机号码/邮箱email代替用户名username登陆

django中有时候需要使用邮箱来登陆,而django默认是使用username来登录,解决办法是什么?

正常的登陆写法如下:

from django.views import View
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login

class LoginView(View):
    def post(self, request):
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)

        user = authenticate(username=username, password=password)  #用户验证
        if user:
            login(request, user)  #用户登录
            return redirect('/index.html')
        return render(request, "login.html")

从上述代码可以看到django登陆主要是基于authenticate,如果我们想要使用手机号码/邮箱来代替,那么可以重写authenticate()

from django.contrib.auth.backends import ModelBackend
from models import Users

class EmailBackend(ModelBackend):
    def authenticate(self, request, email=None, password=None, **kwargs):
        if email is None:
            phone = kwargs.get('phone')
            if phone is None:
                return None
            else:
                try:
                    user = Users.objects.get(phone=phone)
                except Users.DoesNotExist:
                    return None
        else:
            try:
                user = Users.objects.get(email=email)
            except Users.DoesNotExist:  # 可以捕获除与程序退出sys.exit()相关之外的所有异常
                return None

        if user.check_password(password):
            return user
            
    def get_user(self, user_id):
        try:
            return Users.objects.get(id=user_id)
        except Users.DoesNotExist:
            return None

然后在setting.py中添加以下代码

AUTHENTICATION_BACKENDS = (
    'app名字.views.CustomBackend',
)

django 使用手机号码/邮箱email代替用户名username登陆

    原文作者:风v月
    原文地址: https://segmentfault.com/a/1190000015414370
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞