Reputation: 57
I am using the django 1.11 version and django rest framework for the rest api I am passing the token value in the HTTP header in React Native using fetch
But when I am trying to retrieve the token value in django views file it is giving me error
In react Native I am passing the token value as below
fetch(url,{
method: 'get',
headers : new Headers({
'token':'token',
'Content-Type': 'application/json'
})
})
I django rest APi I am trying to fetch the token value as below
def get(self,request,**kwargs):
token = request.headers['token']
queryset=models.Schedule.objects.filter()
serializer_class= RepScheduleSerializer(queryset,many=True)
return Response(serializer_class.data)
But it is giving me error Request object has no attribute headers
I want to fetch the token value in the function
Upvotes: 1
Views: 9198
Reputation: 477308
The headers of a request are stored in the request.META
dictionary [Django-doc]. You thus should alter the code to:
def get(self,request,**kwargs):
token = request.META['HTTP_TOKEN']
queryset = models.Schedule.objects.all()
serializer_class = RepScheduleSerializer(queryset,many=True)
return Response(serializer_class.data)
Right now however, you do not do anything with this token. You thus might need to alter the logic.
Note that the keys are pre-processed:
With the exception of
CONTENT_LENGTH
andCONTENT_TYPE
, as given above, any HTTP headers in the request are converted toMETA
keys by converting all characters to uppercase, replacing any hyphens with underscores and adding anHTTP_
prefix to the name. So, for example, a header calledX-Bender
would be mapped to the META keyHTTP_X_BENDER
.
Since django-2.2, there is the request.headers
dictionary-like object [Django-doc], that allows case-insensitive lookups. Based on the error message, you however do not use django-2.2.
Upvotes: 3