Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of validate method #67

Open
JerzySpendel opened this issue Jan 16, 2019 · 1 comment
Open

Implementation of validate method #67

JerzySpendel opened this issue Jan 16, 2019 · 1 comment

Comments

@JerzySpendel
Copy link
Contributor

Let's look at:

class TokenObtainPairSerializer(TokenObtainSerializer):
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super(TokenObtainPairSerializer, self).validate(attrs)

        refresh = self.get_token(self.user)

        data['refresh'] = text_type(refresh)
        data['access'] = text_type(refresh.access_token)

        return data

Why refresh and access fields are added in validate method? This method is supposed to validate data returned by to_internal_value, why not add those to keys in to_internal_value?

In my case, I had to override TokenObtainPairSerializer in the following way:

class CustomTokenObtainPairSerializer(CustomTokenObtainSerializer, TokenObtainPairSerializer):
    access = serializers.CharField(read_only=True)
    refresh = serializers.CharField(read_only=True)

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        data['refresh'] = text_type(refresh)
        data['access'] = text_type(refresh.access_token)

        return data

I had to explicitly declare these two fields under class statement, otherwise I have been receiving:

KeyError: "Got KeyError when attempting to get a value for field email on serializer CustomTokenObtainPairSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'email'."

@sshishov
Copy link

Just a question, why did you base your serializer from two classes, including your custom CustomTokenObtainSerializer?
In my case I inherited from TokenObtainPairSerializer to create my serializer and wrote validate method to send signal user_logged_in. Everything works as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants