3

I'm using the Django REST framework and I'm trying to get the user like this in one of my class-based views:

class ListPDF(PDFTemplateView):
    """
    Return a PDF 
    """
    permission_classes = (IsAuthenticated,)
    template_name = 'pdf.html'

    def get_context_data(self, **kwargs):
        user = User.objects.get(id=self.request.user.id)

but for some reason I keep getting the error User matching query does not exist. I'm using the rest_framework.authtoken for authentication.

I've investigated and when I don't log in through the admin section the user is anonymous even though the user token is sent with the request. How do I get the user object in this view?

**Update

I found this answer:

from rest_framework.authtoken.models import Token
user = Token.objects.get(key='token string').user

but is there not an easier way to get the user?

Isaac Joy
  • 85
  • 4
  • 14

1 Answers1

2

Make sure you have added TokenAuthentication to DEFAULT_AUTHENTICATION_CLASSES:

# settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    ...
]

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    ...
}

Docs: http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication


Edit: I've noticed that you are subclassing PDFTemplateView. Did you write it yourself? Is it inherited from the DRF's APIView?

Max Malysh
  • 29,384
  • 19
  • 111
  • 115