Search code examples
pythondjangodjango-rest-frameworkdjango-rest-framework-jwt

Django Rest Framework JWT - Custom Payload with Extend User


I have an Extended User with sample serializers (Profile is Extend User, not Abstract User)

 {
    "id": 3,
    "url": "http://localhost:8000/api/v1/users/demo/",
    "username": "demo",
    "first_name": "First",
    "last_name": "Demo",
    "profile": {
        "gender": null,
        "location": "Sa Pa",
        "date_of_birth": null,
        "job_title": null,
        "phone_number": null,
        "fax_number": "",
        "website": "",
        "intro": "",
        "bio": "",
        "interested_in": null,
        "languages": null,
        "quotes": null,
        "nickname": null
    }
}

How can I custom payload with all above fields and get it with axios? Now it just get payload:

authUser:Object
email:"test@gmail.com"
exp:1509183691
user_id:1
username:"First Demo"
token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImxlY29uZ3RvYW4iLCJ1c2VyX2lkIjoxLCJlbWFpbCI6ImRyYWZ0bGlnb25ncXVhbjdAZ21haWwuY29tIiwiZXhwIjoxNTA5MTgzNjkxfQ.KSEp-7g-SGDbqfspedNwkT1rABFi0UQ45yKDJDTX2zA"

I followed with this link: #145 but isn't work Please help me!


Solution

  • Here is what I did:

    • create your own jwt_response_payload_handler:

      from your_serializers import UserSerializer
      
      def jwt_response_payload_handler(token, user=None, request=None):
          return {
              'token': token,
              'user': UserSerializer(user, context={'request':request}).data
          }
      
    • put your custom response payload handler into your settings.py file:

      JWT_AUTH = {
          ...,                
          'JWT_RESPONSE_PAYLOAD_HANDLER': 'path_to.jwt_response_payload_handler',
          ...
      }
      

    When you login you get back token and user with your serialized data.