[Answered ]-Call a particular function of Class based view Django from urls.py

1👍

You can make the method as static and refer to this method from urls.py as:

# views.py
class ProductView(views.APIView):

    @staticmethod
    def get_featured_products(request):
        #some code here
        return None
        

# urls.py        
urlpatterns = [
    path('featured_products', ProductView.get_featured_products)
]

0👍

You can list it as any other class-based view in your urls.py using .as_view() but you will always have to have queryset as a class variable in your class that inherits from views.APIView.

Your view has to be defined like this

class ProductView(APIView):
    queryset = Product.objects.all() # Here put your own queryset, for me if I dont i get error

    def get(self, request):
        print("GET REQUEST")
        return Response({"hello" : "world"})
    
    # you can similarly define other methods such as post, put like you already have

And then in your urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    # You'll obviously have to import it if it is not  in the same file
    path('featured_products', ProductView.as_view()) 
]

0👍

For any class-based view, the urls.py can only contain ProductView.as_view(). It is not possible to directly refer to a method within a class.

as_view() function calls an instance of the class and returns a response based on the following methods:’get’, ‘post’, ‘put’, ‘patch’, ‘delete’, ‘head’, ‘options’, ‘trace’

If your method doesn’t match the above, as is the case, you will get a HTTPresponseNotAllowed error.

You may place the method within one of the allowed methods and make it run.

You may check this link to know more: https://djangodeconstructed.com/2020/01/03/mental-models-for-class-based-views/

👤Vijay

Leave a comment