django的自定义用户,自定义用户验证
介绍
django的自定义用户和自定义用户验证是常用操作,但是新手很容易搞迷糊
本文整理一下
自定义用户
# 先定义用户model
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
birday = models.DateField(verbose_name=u"生日", null=True, blank=True)
gender = models.CharField(max_length=6, choices=(("male",u"男"),("female","女")), default="female", verbose_name="性别")
address = models.CharField(max_length=100, default=u"",null=True, blank=True, verbose_name="地址")
image = models.ImageField(upload_to="image/%Y/%m",default=u"image/default.png", max_length=100)
mobile = models.CharField(max_length=11, null=True, blank=True,verbose_name="电话")
email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱")
class Meta:
verbose_name = "用户信息"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.username
def __str__(self):
return self.username
#setting中配置
AUTH_USER_MODEL = "users.UserProfile"
# 要使用User对象的时候
from django.contrib.auth import get_user_model
User = get_user_model()
if User.objects.filter(email=email).exists():
raise serializers.ValidationError("该邮箱已经注册。")
自定义用户验证
# 默认用户验证是使用username,这里改为username和email都可以
from django.contrib.auth import get_user_model
User = get_user_model()
class CustomBackend(ModelBackend):
"""
自定义用户验证
""" def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = User.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except User.DoesNotExist:
logger.warning(f'User does not exist: {username}')
return None
except Exception as e:
logger.error(f'Error during authentication: {e}')
return None
# setting中配置
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend',
)
# 使用的时候
# 验证用户名和密码
from django.contrib.auth import authenticate
user = authenticate(username=username, password=password)
if user is None or not user.is_active:
raise serializers.ValidationError("用户名或密码错误")
attrs['user'] = user
return attrs