django-rest-frameworktestcasedjango-tests

Add Token to headers request in TEST mode DRF


how is possible to add 'Authorization': 'Token' to TEST request in Django/DRF?

If i use simple requests.get(url, headers={'Authorization': 'Token'} all work perfect but how to do such request in TestCase?


Solution

  • Ref: http://www.django-rest-framework.org/api-guide/testing/#credentialskwargs

    from rest_framework.authtoken.models import Token
    from rest_framework.test import APIClient
    
    # Include an appropriate `Authorization:` header on all requests.
    token = Token.objects.get(user__username='lauren')
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)