当我创建新用户时,他的密码在数据库中保持未加密状态。
这是我的models.py文件:
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from .managers import UserManager
class UserProfile(AbstractBaseUser):
phone = models.CharField(max_length=100, unique=True, db_index=True, primary_key=True)
objects = UserManager()
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
def get_full_name(self):
return self.phone
def get_short_name(self):
return self.phone
serializers.py:
class UserProfileSerializer(serializers.ModelSerializer):
phone = serializers.CharField(required=True, allow_blank=False)
password = serializers.CharField(required=True, allow_blank=False, write_only=True)
class Meta:
model = UserProfile
fields = '__all__'
extra_kwargs = {'password': {'write_only': True}}
views.py:
class UserProfileViewSet(ModelViewSet):
serializer_class = UserProfileSerializer
queryset = UserProfile.objects.all()
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(data=serializer.data, status=HTTP_200_OK)
managers.py:
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, phone, password, **extra_fields):
if not phone or not password:
raise ValueError('Err!')
user = self.model(phone=phone, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, phone, password, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(phone, password, **extra_fields)
def create_superuser(self, phone, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(phone, password, **extra_fields)
在settings.py中的我写道:
AUTH_USER_MODEL = 'users.UserProfile'
使用print,我发现在创建用户时没有使用UserManager方法。我究竟做错了什么?
答案 0 :(得分:2)
您正在回答自己的问题:您没有使用管理员方法来创建用户,而只是保存数据。实施UserProfileSerializer.save
并在其中调用User.objects.create_user
,而不是使用ModelSerializer.save
(它不知道您的模型是用户模型)。
答案 1 :(得分:0)
在serializers.py中编写创建方法:
class UserProfileSerializer(serializers.ModelSerializer):
phone = serializers.CharField(required=True, allow_blank=False)
password = serializers.CharField(required=True, allow_blank=False, write_only=True)
class Meta:
model = UserProfile
fields = '__all__'
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
return UserProfile.objects.create_user(**validated_data)
参考: https://www.django-rest-framework.org/api-guide/serializers/#saving-instances