# 前提
继承 django 自带的用户类(AbstractUser)
# 环境
1. python: 3.6.x
2. django==1.11.22
# apps/users/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserProfile(AbstractUser):
"""
用户
"""
gender_choice = (
("1", "男"),
('0', "女"),
)
email = models.EmailField(verbose_name='邮箱', max_length=255, unique=True)
phone = models.CharField(verbose_name="手机号码", max_length=50, null=True, blank=True)
avatar = models.URLField(verbose_name="用户头像", default="http://photo.xxx.top/avatar_default.png")
gender = models.CharField(max_length=32, choices=gender_choice, default="男", verbose_name="性别")
time_black = models.DateTimeField(verbose_name="下次可访问时间", blank=True, null=True)
last_ip = models.GenericIPAddressField(verbose_name="上次访问IP", default="0.0.0.0")
class Meta:
verbose_name = "用户信息"
verbose_name_plural = "用户信息列表"
def __str__(self):
return "%s-%s %s" % (self.username[0].upper(), self.last_name, self.first_name)
# apps/users/views.py(不局限于邮箱,也可以改成 手机号码等等,但是要注意字符类型)
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import UserProfile
# Create your views here.
# 让用户可以用邮箱登录
# setting 里要有对应的配置 AUTHENTICATION_BACKENDS
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
注意:当报错误 {"non_field_errors":["无法使用提供的认证信息登录。"]},请尝试在 authenticate 里面加上 request,如:authenticate(self, request, username=None, password=None, **kwargs)
# settings.py
ALLOWED_HOSTS = ["*"]
AUTH_USER_MODEL = 'users.UserProfile'
AUTHENTICATION_BACKENDS = (
'apps.users.views.CustomBackend', # AUTH 方法(支持邮箱登录),CustomBackend 的路径
)