// models.py
hello from services
// views.py
class UserManager(BaseUserManager):
def create_user(self, email, name, password=None):
if email is None:
raise TypeError('email is empty')
user = self.model(email=email, name=name)
user.set_password(password)
user.save(using= self.db)
return user
class UserProfile(AbstractBaseUser, PermissionMixin):
email = models.EmailField(unique=True)
name = models.CharField(max_length=500)
password = models.CharField(max_length=300)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
objects = UserManager()
// serializers.py
class UserAPIView(viewsets.ModelViewSet):
permission_classes = (IsOwnerOrReadOnly,)
serializer_class = RegistrationSerializer
queryset = UserProfile.objects.all()
def post(self, request):
user = request.data.get('user', {})
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
这是我应用程序的一部分。我需要在此应用中设置class RegistrationSerializer(serializers.ModelSerializer):
class Meta:
extra_kwargs = { 'password' : { 'write_only' : True }}
model = UserProfile
fields = ('id','email','name','password','is_staff')
def create(self, validated_data):
return UserProfile.objects.create_user(**validated_data)
或patch()
函数,以便应正确更新update()
字段,即password
字段必须使用set_password( )