Home > Software design >  In Django, can I use context in redirect?
In Django, can I use context in redirect?

Time:06-25

I am trying to use redirect with context but I get a NoReverseMatch exception. Code is as follows:

return redirect(reverse('td:success', kwargs={ 'data': my_data }))

When I use render, all goes well and I am able to access the context in the template. But I want redirect instead.

enter image description here

CodePudding user response:

But I want redirect instead.

You can't. The redirect(…) function [Django-doc] simply returns a HTTP response that contains the URL to visit next. The browser will then visit that URL, it is thus the browser that makes the next HTTP request, and the previous request and response are "destroyed". You thus need the database, cookies, session variables, URL parameters, etc. to pass data between the two requests.

If you use a URL parameter, you can thus add data to this. In that case, your code snippet can be simplified to:

return redirect('td:success', data=my_data)

there is no need to work with reverse(…) since redirect(…) will call reverse(…) internally.

  • Related