django-rest-framework Token Authentication With Django Rest Framework GETTING THE USER TOKEN


Token authentication functionality assigns a token to a user, so each time you use that token, the request object will have a user attribute that holds the user model information. Easy, isn’t it?

We’ll create a new POST method to return the token for this user, as long as the request holds a correct user and password. Open located at test_app application folder.

from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.exceptions import ParseError
from rest_framework import status
from django.contrib.auth.models import User
# Create your views here.
class TestView(APIView):
    def get(self, request, format=None):
        return Response({'detail': "GET Response"})
    def post(self, request, format=None):
            data = request.DATA
        except ParseError as error:
            return Response(
                'Invalid JSON - {0}'.format(error.detail),
        if "user" not in data or "password" not in data:
            return Response(
                'Wrong credentials',
        user = User.objects.first()
        if not user:
            return Response(
                'No default user, please create one',
        token = Token.objects.get_or_create(user=user)
        return Response({'detail': 'POST answer', 'token': token[0].key})