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

Community
  • 1
  • 1
cutteeth
  • 2,148
  • 3
  • 25
  • 45
  • 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? – GwynBleidD Sep 25 '15 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 – cutteeth Sep 25 '15 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. – GwynBleidD Sep 25 '15 at 14:57
  • It would be very helpful if you exemplify a bit more. – cutteeth Sep 25 '15 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: http://stackoverflow.com/q/26790981/399435 – Karthic Raghupathi Sep 11 '16 at 23:40

0 Answers0