2019独角兽企业重金招聘Python工程师标准>>>
django 修改默认的user表和默认的认证系统
django的功能非常强大,但是自带的user表很多情况下并不满足我们的需求,因此我们需要修改其默认的user表,并且把用username登录改成用email登录
第一步,创建自己的user表,在创建的app下的models中
from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
class UserProfile(AbstractUser):
nick_name = models.CharField(max_length=50, verbose_name='昵称', default='')
birthday = models.DateField(null=True, blank=True, verbose_name='生日')
gender = models.CharField(max_length=6, choices=(('male', '男'), ('female', '女')), default='female', verbose_name='性别')
address = models.CharField(max_length=100, default='', verbose_name='地址')
mobile = models.CharField(max_length=11, null=True, blank=True, verbose_name='手机号')
image = models.ImageField(max_length=100, upload_to='image/%Y/%m', default='image?default.png', verbose_name='头像')
class Meta:
verbose_name = '用户信息'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
因为django的user表也是继承自AbstractUser,所以我们也这样做
然后修改下setting,添加
# UserProfile 覆盖了 django 内置的 user 表
AUTH_USER_MODEL = 'users.UserProfile'
appname.userProfile
接着修改认证系统
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from models import UserProfile
# 让用户可以用邮箱登录
# setting 里要有对应的配置
class CustomBackend(ModelBackend):
def authenticate(self, 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
记得引入models中创建的表
# AUTH 方法(支持邮箱登录)
AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)
setting中加入该方法
完成