1

我这样创建了自定义用户模型:

class UserAccount(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def __str__(self):
        return self.email

经理:

class UserAccountManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        if not email:
            raise ValueError('Users must have unique email address')

        email = self.normalize_email(email)
        user = self.model(email=email, name=name)

        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, email, name, password):
        user = self.create_user(email, name, password)

        user.is_superuser = True
        user.is_staff = True
        user.save()

        return user

我已经打电话给user.set_password(password)经理,但它没有散列它。为此,我无法登录!这是我用于注册过程的视图:

class SignupView(APIView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        data = self.request.data

        name = data['name']
        email = data['email']
        password = data['password']
        password2 = data['password2']

        if password == password2:
            if User.objects.filter(email=email).exists():
                return Response({'error': 'Email already exists'})
            if len(password) < 6:
                return Response({'error': 'Password must be more than 6 characters in length'})
            user = User.objects.create(email=email, password=password, name=name)
            user.save()
            return Response({'success': 'User created successfully'})
        return Response({'error': 'Passwords do not match'})

我见过其他解决方案,但它们与序列化程序有关。就我而言,我没有使用任何序列化程序。我该如何解决?

4

1 回答 1

1

你不应该打电话.create(…),但是.create_user(…)

class SignupView(APIView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        data = self.request.data

        name = data['name']
        email = data['email']
        password = data['password']
        password2 = data['password2']

        if password == password2:
            if User.objects.filter(email=email).exists():
                return Response({'error': 'Email already exists'})
            if len(password) < 6:
                return Response({'error': 'Password must be more than 6 characters in length'})
            user = User.objects.create_user(email=email, password=password, name=name)
            user.save()
            return Response({'success': 'User created successfully'})
        return Response({'error': 'Passwords do not match'})
于 2020-05-25T14:09:10.313 回答