我正在使用django-rest-framework-simplejwt,想知道注册用户后是否可以返回令牌?

This帖子提供了另一个jwt包的解决方案,我想知道如何为simplejwt做类似的事情?

谢谢

最佳答案

我刚刚解决了自己的问题。让我知道您是否有任何意见。谢谢!

serializers.py

class RegisterUserSerializer(serializers.ModelSerializer):
    """Serializer for creating user objects."""

    tokens = serializers.SerializerMethodField()

    class Meta:
        model = models.User
        fields = ('id', 'password', 'email', 'tokens')
        extra_kwargs = {'password': {'write_only': True}}

    def get_tokens(self, user):
        tokens = RefreshToken.for_user(user)
        refresh = text_type(tokens)
        access = text_type(tokens.access_token)
        data = {
            "refresh": refresh,
            "access": access
        }
        return data

    def create(self, validated_data):
        user = models.User(
            email=validated_data['email']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user


views.py

class UserListView(generics.ListCreateAPIView):
    """Handles creating and listing Users."""
    queryset = User.objects.all()

def create(self, request, *args, **kwargs):
        serializer = RegisterUserSerializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

08-05 02:22