Nidhi
Nidhi

Reputation: 57

Attribute Error : 'Request' object has no attribute 'headers'- Django

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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 and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

Since , 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 .

Upvotes: 3

Related Questions