Redirecting after user input is submitted


I am having a view called home with some form and a submit button. The data put into the form is going to be used to calculate some math. After submitting I want to show the user the calculated result on a new view. Therefore i figured redirecting would be the best way to do that. I am redirecting as follows:

def home(request):
    if request.method == 'POST':
        form = BoxSize(request.POST)
        if form.is_valid(): 
            data = form.cleaned_data
            return redirect("result", data=data)

the result view :

def result(request, data):
    return render(request,'mysite/result.html', {'data' : data)


path('result/', result, name="result")

Now i get a error: NoReverseMatch

So i guess, there is a problem with the urls definition as it is missing the ‘data’ parameter in the def results(). Am i on the right track - in the sense how it is supposed to be done in django? I had it working if i render directly in the def home() instead of redirecting. But it felt that it would be cleaner if it is redirected to the actual view. Thanks

Yes you could do something like this, but this isn’t the “typical Django-style” pattern.

In the more traditional mode, you would either:

  • Save the results of the calculation in a model or in the session, then redirect to a view that displays the contents of that model (or session).

  • Have the form post to the other view that performs the calculation there, and renders the result.

Now, to address the specific error you are receiving, the is that you’re trying to pass data as a parameter for the url, which means your url needs to be defined to accept that parameter:

would need to become something like:
path('result/<str:data>/', result, name="result")

See Example #2 in the docs for redirect along with the referenced docs for reverse.

1 Like