Micromegas
Micromegas

Reputation: 1689

How to call a class based generic API view from a custom function based view

I am having some problems and doubts about how to call my own API within my app.

So I have an API to which I can send data. What I want to do in a different view is calling this sent data so I can visualize it in a template.

First I was trying to call the API with the library requests inside of my view. Even though that works I am having problems with authentication. So I was thinking I could call my class based API view from my custom function based view.

But I don't know if that is possible, nor do I know if that is recommendable. I was also thinking that it might be better to do that with javascript? I don't know.... So my question is twofold:

a) What is the best practice to call an API view/get API data from my own app so that I can manipulate and visualize it

b) If this is good practice, how can I call my class based generic API view from my custom function based view?

Here is what I am trying so far:

my generic view

class BuildingGroupRetrieveAPIView(RetrieveAPIView):
    """Retrieve detail view API.

    Display all information on a single BuildingGroup object with a specific ID.

    """

    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication, BasicAuthentication]
    serializer_class = BuildingGroupSerializer
    queryset = BuildingGroup.objects.all()

my function based view with which I try to call it:

def visualize_buildings(request, id):
    returned_view = BuildingGroupRetrieveAPIView.as_view()
    return returned_view


my url

    path('data/<int:pk>/', BuildingGroupRetrieveAPIView.as_view(),
         name="detail_buildings_api"),

When I call my class based view I get AttributeError: 'function' object has no attribute 'get'

Help is very much appreciated! Thanks in advance!

Upvotes: 0

Views: 2009

Answers (2)

D.W
D.W

Reputation: 530

Correct way:

from django.url import reverse, resolve

def get_view_func(name_of_your_view):
    return resolve(reverse(name_of_your_view)).func

# if your are in a drf view:
get_view_func()(request._request)

# if you are in normal django view:
get_view_func()(request)

Upvotes: 0

Higor Rossato
Higor Rossato

Reputation: 2046

What you can do if you want is to call your CBV after its declaration inside its file for the sake of easiness when declaring its URL.

views.py

class BuildingGroupRetrieveAPIView(RetrieveAPIView):
    .....


visualize_buildings = BuildingGroupRetrieveAPIView.as_view()

Then on your URLs, you use that name.

urls.py

from . import views


path('data/<int:pk>/', views.visualize_buildings, name="detail_buildings_api"),

Upvotes: 1

Related Questions