6.3使用用户名或邮箱都能登录

首先在settings配置里面添加backend:

AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
)

在 users > views.py中添加backend函数:

# 实现 用户名和邮箱都可以登录
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

修改后的views.py内容是:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile
from django.db.models import Q


# Create your views here.


def user_login(request):
    if request.method == 'GET':
        return render(request, 'login.html', {})
    if request.method == 'POST':
        user_name = request.POST.get('username', '')
        pass_word = request.POST.get('password', '')
        # 成功返回user,失败返回None
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:
            login(request, user)  # 直接登录
            return redirect('home')
        else:
            return render(request, 'login.html', {'msg': '用户名或密码错误。'})


# 实现 用户名和邮箱都可以登录
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

猜你喜欢

转载自www.cnblogs.com/andu99/p/8986799.html

相关文章