django 通过邮箱和用户名都能登录

Posted 雪落忆海

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django 通过邮箱和用户名都能登录相关的知识,希望对你有一定的参考价值。

一、

在settings.py 文件中的#Application definition 下增加代码:

AUTHENTICATION_BACKENDS=( users.views.CustomBackend , )

注意上面的括号里,别忘了加逗号!

二、

在users/views.py中加代码:

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import UserProfile


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

 

以上是关于django 通过邮箱和用户名都能登录的主要内容,如果未能解决你的问题,请参考以下文章

java读取邮件时报错,不知道什么原因,求指教,我用户名和密码都是正确的,在网站能登录看邮件

Linux新建用户可以在shell中切换到该用户也能登录到图形桌面

Linux新建用户可以在shell中切换到该用户也能登录到图形桌面

Oracle数据库,我把用户删除了,但是plsql中还能登录

facebook 重装电脑后能登录

解决MySQL不需要密码就能登录问题