5

I am trying to call an api made with Django Rest Framework drf. My case is that I want to call the api from another view get the response and display the data in a template. I have referred to this SO post, but could not make a successful call since my viewset requires authentication. Viewset works perfect if called using urls, the default way. Viewset is as below

class ViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Objects to be viewed or edited.
    """
    permission_classes = (permissions.IsAuthenticated,)
    queryset = Myclass.objects.all()
    serializer_class = MyclassSerializer
    ....
    ....
    return response(json)

On calling this api from another view the response that I get is a 401 page from drf api.

 ipdb>view = Myview.as_view({'get':'list'}
 ipdb>obj=view(request, *args, **kwargs)
 ipdb> obj.data
 {u'detail': u'Authentication credentials were not provided.'}
 ipdb>obj.has_header('Authentication')
 False 

I tried passing Authentication headers also, but I dont know whether its the right way.

  view = MyViewSet.as_view({'get':'list'},{'token':'token'})

This returned an error argument token is not accepted. And I tried

view = MyViewSet.as_view({'get':'list'},Authentication={'token':'token'})

But this Also returned me errors. How is it possible to call an api viewset from another view by passing auth params?

TIA

5
  • Why do you want to call whole view? Can't it be done by re-using MyClassSerializer and maybe some other parts from that view in your second view? Commented Sep 25, 2015 at 12:58
  • 1
    Its like I am using api and I don't want to rewrite the view in django ORM. I want to fetch data as json using drf api and return template using django views Commented Sep 25, 2015 at 14:16
  • You can use serializer here to deal with it - if there is noting in view that is doing something more around your data, it won't be hard. Commented Sep 25, 2015 at 14:57
  • It would be very helpful if you exemplify a bit more. Commented Sep 25, 2015 at 15:15
  • 1
    I believe if you pass the incoming request directly to your other view, the authentication should work. Here is the example on SO: stackoverflow.com/q/26790981/399435 Commented Sep 11, 2016 at 23:40

0

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.