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

Alessio
  • 3,404
  • 19
  • 35
  • 48
Aseem
  • 5,848
  • 7
  • 45
  • 69
  • 2
    https://stackoverflow.com/a/59764296/433570 you can call a function instead of doing 'network request' as are doing now. – eugene May 12 '20 at 05:00

1 Answers1

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
Aseem
  • 5,848
  • 7
  • 45
  • 69