title: How do I set up token authentication properly with Django Rest Framework?
body: <p>I am using DRF 1.10 and Python 3.5.</p>
  
  <p>I am trying to use DRF's <code>rest_framework.authtoken.models.Token</code> to authenticate a user on login. This is what I have:</p>
  
  <p><code>views.py</code></p>
  
  <pre><code>class LoginView(views.APIView):
      serializer_class = LoginSerializer
  
      def post(self, request, **kwargs):
          serializer = self.serializer_class(data=request.data)
          if serializer.is_valid():
              user = User.objects.get(username=serializer.data['username'])
              token = Token.objects.create(user=user)
  
              response = {}
              response['user'] = serializer.data
              response['token'] = token.key
  
              return Response(response, status=status.HTTP_200_OK)
          return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  </code></pre>
  
  <p><code>serializers.py</code></p>
  
  <pre><code>class LoginSerializer(serializers.Serializer):
      username = serializers.CharField()
      password = serializers.CharField()
  
      def validate(self, attrs):
          username = attrs.get("username").lower()
          password = attrs.get("password")
  
          user = authenticate(username=username, password=password)
  
          if user:
              attrs["user"] = user
              return attrs
          else:
              raise serializers.ValidationError(
                  "Unable to login with credentials provided."
              )
  </code></pre>
  
  <p>On login I want to provide the user with a token and on log out I want to delete that token. The problem is that when I attempt to delete the token by finding the token with the token's key and the user that it is related to, I am unable to find the token. The logout view is here:</p>
  
  <pre><code>class LogoutView(views.APIView):
      def post(self, request, **kwargs):
          try:
              token = request.META['HTTP_AUTHORIZATION'].split(" ")[1]
              invalidate_token = Token.objects.filter(key=token, user=request.user)
              invalidate_token.delete()
  
          return Response({ detail: "Logged out"}, status=status.HTTP_202_ACCEPTED)
      except:
          return Response({"error": ["Token does not exist!"]}, status=status.HTTP_400_BAD_REQUEST)
  </code></pre>
  
  <p>I ran into problems when I tried to log a user out. I realized that <code>request.user</code> was still an <code>AnonymousUser</code> and not a <code>User</code>. How do I go about fixing this?</p>
  
  <p><a href="https://i.stack.imgur.com/FpJaA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FpJaA.png" alt="Header from Postman"></a></p>
  
  <p>This is my header in postman.</p>