return token after registration with django-rest-framework-simplejwt

后端 未结 3 1918
独厮守ぢ
独厮守ぢ 2021-02-04 22:46

I\'m using django-rest-framework-simplejwt and was wondering if it\'s possible to return a token after registering a user?

This post has a solution for another jwt packa

3条回答
  •  遥遥无期
    2021-02-04 23:23

    I just solved my own question. Let me know if you have any comments. Thanks!

    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)
    

提交回复
热议问题