新建Backend类

from django.contrib.auth.backends import ModelBackend
from django.shortcuts import render

from django.http import HttpResponse
# Create your views here.

from django.contrib.auth import get_user_model
from django.db.models import Q

User = get_user_model()  # 须在settings里配置AUTH_USER_MODEL = 'users.UserProfile'

class CumstomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username)|Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

配置settings

AUTH_USER_MODEL = 'users.UserProfile'
AUTHENTICATION_BACKENDS=(
    'users.views.CumstomBackend',
)

 

posted on 2019-04-05 17:22  chester·chen  阅读(981)  评论(0编辑  收藏  举报