JWT auth没有为Django中的自定义用户模型创建令牌?

hgqdbh6s  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(123)

我有以下问题:我为jwt auth创建了一个自定义UserModel和Djoser。当我通过终端创建一个超级用户时,它使用哈希密码创建,但当我使用APIVIEW创建时,它不使用哈希创建,因此当我需要为创建的用户创建令牌时,它给我"detail": "No active account found with the given credentials",但当我为超级用户创建令牌时,它成功创建。
我的自定义用户模型:

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError(_("Please enter your email address"))

        email = self.normalize_email(email)
        new_user = self.model(email = email, **extra_fields)
        new_user.set_password(password)
        new_user.save()

        return new_user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Super user should have is_staff True'))
        
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Super user should have is_superuser True'))

        if extra_fields.get('is_active') is not True:
            raise ValueError(_('Super user should have is_active True'))

        return self.create_user(email, password, **extra_fields)

class User(AbstractUser):
    username = models.CharField(max_length=200, unique=True)
    email = models.EmailField(max_length=200, unique=True)
    phone_number = PhoneNumberField(null=False, unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'phone_number']
    objects = CustomUserManager()

    def __str__(self):
        return self.username

用户视图:

class UserView(APIView):
    def get(self, request):
        user = User.objects.all()
        serializer = UserCreationSerializer(user, many = True)
        return Response(serializer.data, status = status.HTTP_200_OK)

    def post(self, request):
        serializer = UserCreationSerializer(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        return Response(status = status.HTTP_406_NOT_ACCEPTABLE)

先谢了。

ojsjcaue

ojsjcaue1#

如果有人感兴趣的话,我终于弄明白了。我的主要问题是我没有一个创建密码函数,当我创建一个用户时,它的密码没有得到散列。我不得不把这个函数添加到我的序列化器中。

def create(self, validated_data):
        user = User.objects.create(
            username = validated_data['username'],
            email = validated_data['email'],
            phone_number = validated_data['phone_number']
        )

        user.set_password(validated_data['password'])
        user.save()

        return user

相关问题