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?
The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.
You can get the token from the request. auth attribute. It returns a DRF Token instance. If you want only the key then you can access it with the request.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With