Nik
Nik

Reputation: 1221

Call view from within another view with modified request

I have a view_A in Django where I want to get data from another view_B. I can't just use the functions from B or modify B because it's something external that I import. So within view_A I would create a request object and pass it to view_B like that:

from django.http import HttpRequest

class view_A(APIView):

    def post(self, request):

        new_request = HttpRequest()
        new_request.method = 'POST'
        new_request.content_type = 'application/json'
        new_request.POST = {"var1": var1, "var2": var2}
        response = view_B(new_request)
        return(response)

However it seems that I am not setting the body of the request correctly as it returns:

{"var1":["This field is required."],"var2":["This field is required."]}

Any idea where I messed up?

Upvotes: 0

Views: 625

Answers (1)

JSS
JSS

Reputation: 174

I would suggest the following code changes, as well as redirect to new view.

from django.shortcuts import redirect, render, reverse

class view_A(APIView):

    def post(self, request, *args, **kwargs):
        if request.method == "POST":
           data = request.POST.dict()
           var1 = data['var1']
           var2 = data['var2']
           # do something with var1 and var2
           # or pass data to another view
           return redirect(reverse('your_url_name', data))

urls.py

path('your_path/', views.view_B.as_view(), name='your_url_name'),

Just as a few code suggestions, I would always check for request.method first, then write logic accordingly. Also, in naming your class view, I would use capitals and no _ as a separator --> class ViewA(APIView) also trying to be more specific in the name as to what the class is supposed to do. It does not seem this class or post request are actually doing anything.

What you are really looking to do here is redirect to view_B passing it context data which can then be accessed in view_B.

Upvotes: 1

Related Questions