0

I have a django rest API which gives list of students to certain authentic users. It needs to be called from a django view. Currently I am using requests library with token authentication inside get_context_data as shown below:

import requests
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    token,created = Token.objects.get_or_create(user=self.request.user)
    reverse_url = 'http://127.0.0.1:8000/api/students/'
    response = requests.get(
         reverse_url,
        headers={'Authorization': 'Token {}'.format(token)}
    )
    context['object'] = response.json()
    return context

Is this the right way of doing it Thanks

1

1 Answer 1

0

Calling the view function instead of a network request is a better way of doing it as mentioned by eugene in the comment.

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    response = LessonViewSet.as_view({'get': 'retrieve'})(
        request=self.request,
        pk=kwargs['pk']
    ).data
    context['object'] = response
    return context
Sign up to request clarification or add additional context in comments.

Comments

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.