自定义django drf JWT响应

时间:2018-06-16 16:43:42

标签: django django-rest-framework

我按照drf文档来自定义响应。我想用JWT获取userdata,但我不能。 谢谢你

  #settings:
    'JWT_PAYLOAD_HANDLER': 
    'spauser.views.jwt_response_payload_handler',

    #views
    def jwt_response_payload_handler(token, user=None, request=None):
        #if I remove spauser, django returns an error: SpaUser matching query does not exist.

        spa_user = SpaUser.objects.get(email= 'test@test.com')
        return {
            'token': token,
            'user': SpaUserSerializer(spa_user, context={'request':request}).data
        }


#serialisers:
    class SpaUserSerializer(serializers.ModelSerializer):

        date_joined = serializers.ReadOnlyField()
        birthdate = serializers.DateField(format="%d-%m-%Y", input_formats=['%d-%m-%Y',], )
        # birthdate = serializers.DateField(format="%d-%m-%Y", input_formats=['%d-%m-%Y',])
        # birthdate = serializers.DateField(input_formats=settings.DATE_INPUT_FORMATS)


        class Meta(object):
            model = SpaUser
            fields = ('id', 'email', 'firstname', 'lastname',
                      'date_joined', 'password',  'birthdate','country')
            extra_kwargs = {'password': {'write_only': True}}

和我的models.py

class SpaUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
    firstname = models.CharField(max_length=30, blank=True)
    lastname = models.CharField(max_length=30, blank=True)
    country= models.CharField(max_length=30, blank=True)
    date_joined = models.DateTimeField(default=timezone.now)
    birthdate = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    jwt_secret = models.UUIDField(default=uuid.uuid4)

    objects = SpaUserManager()
    USERNAME_FIELD = 'email'
    def __str__(self):
        return self.email

test@test.com就是一个例子,我尝试了所有的论坛,但我找不到解决方案。

1 个答案:

答案 0 :(得分:0)

在设置中用JWT_RESPONSE_PAYLOAD_HANDLER替换JWT_PAYLOAD_HANDLER