Reputation: 73
I'm new to Django world and I'm trying to build a Django application with 2 function based views wherein one function/view should be able to call the other view. The reason I'm trying to do this is to reduce avoid writing the logic again which is available in my other API.
@api_view(['POST'])
def PerformActionOne(request):
result_one = PerformActionTwo(request)
result_two = DoSomethingElse(result_one)
return Response(result_two)
@api_view(['POST'])
def PerformActionTwo(request):
# Performs some calculation and returns rest_framework.response Response with some data in it
# result is a dictionary
result = Calculate()
return Response(result)
In the above code I'm getting an error in this line result_one = PerformActionTwo(request)
Error: Exception Type: AssertionError Exception Value:
Therequest
argument must be an instance ofdjango.http.HttpRequest
, notrest_framework.request.Request
.
I tried to look it up online and read documentation but I couldn't get a solution to this. I apologize if this is a duplicate question. Any leads on this will be greatly appreciated.
Upvotes: 4
Views: 2059
Reputation: 1392
not for certain on this but it's possible that the django.http.HttpRequest
object is on the rest_framework.request.Request
object under the _request
param. Maybe try logging request._request
to see what type of object it is?
Upvotes: 4
Reputation: 147
@api_view
is a decorator that converts your function based view into a class based view (see Class-based Views)
The root of what you actually ran into is it adds some wrapper that converts the argument passed into a view from django.http.HttpRequest
into rest_framework.request.Request
. This way when you pass the request
into a function PerformActionTwo
, the view cannot convert the object properly, as it is not of type django.http.HttpRequest
anymore.
As far as I understand if your primary goal is to reuse the code, you should extract the body of your PerformActionTwo
function into a separate function and not decorate it with @api_view
, this way you can call it from any of your decorated functions.
Upvotes: 2