1

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

1 Answer 1

3

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 .

Sign up to request clarification or add additional context in comments.

5 Comments

This didnt worked Its giving me error key error u'token' when I print the request.META value there is no token key
@Nidhi: are you sure the request is triggered by the ract-native request, and not by another request?
@Nidhi: hold on, the tokens are written in uppercase at the server side.
@Nidhi: you probably should look for HTTP_TOKEN.
Yup I got the value its was on HTTP_TOKEN Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.