[Django]-Django REST Framework ObtainAuthToken User Login Api view

8πŸ‘

βœ…

In the docs it tell that you can override the return response of the post request in ObtainAuthToken:

If you need a customized version of the obtain_auth_token view, you
can do so by subclassing the ObtainAuthToken view class, and using
that in your url conf instead.

For example, you may return additional user information beyond the
token value:

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })

And in your urls.py:

urlpatterns += [
    url(r'^api-token-auth/', CustomAuthToken.as_view())
]
πŸ‘€Linh Nguyen

Leave a comment