Home > other >  Django: pass request and response as view parameters
Django: pass request and response as view parameters

Time:06-19

I have a view which takes two parameters (request, response). But when this view is called i get an error which saying - "figure() missing 1 required positional argument: 'response' "

views.py:

def figure(request, response):

    print("request ->", request)
    figures = add_data_to_class(request)
    figures_dict = []
    for figure in figures:
        figures_dict.append({
            "date":figure.date,
            "price_new":figure.price_new,
            "price_used":figure.price_used,
         })
    print(figures_dict)

    context = {"figures":figures_dict}
    return render(response, "app1/figure_data_page.html", context, RequestContext(request))

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.figure, name="figure")
]

figure_data.html

<form action="main\app1\views.py" method="post" id="figure_choice_form">
    <label for="id">Enter ID</label>
    <input type="text" id="id">
</form>

CodePudding user response:

When the url that the view is connected to is accessed, the view is only provided with a 'request' not a 'response'. The response is essentially generated from the render function.

Your render fuction should look like this (with response replaced with request):

return render(request, "app1/figure_data_page.html", context, RequestContext(request))

CodePudding user response:

A view receives a request "give me a page at this URL" and returns a response "Ok - here's a template and some context". In your view, the response is returned by the render() function, and the render function wants the request as the first argument - you're giving a response instead.

If you want to access the view's response, you could assign it to a variable rather than return it (you'd have to actually return it or something similar later).

 response = render(request, "app1/figure_data_page.html", context, RequestContext(request))
 print(response)
 context['response'] = response

But asking for it as a view argument doesn't make a great deal of sense (unless you need the response for a totally different view) as the view is supposed to generate the response itself.

  • Related