I have a simple form, that when submitted redirects to a success page.
I want to be able to use the data that was submitted in the previous step, in my success page.
As far as I know, you can't pass POST data when redirecting, so how do you achieve this?
At the moment I'm having to just directly return the success page from the same URL, but this causes the dreaded resubmission of data when refreshed.
Is using request.session
the only way to go?
You can now perform a redirect with Django, either by using the redirect response classes HttpResponseRedirect and HttpResponsePermanentRedirect , or with the convenience function django. shortcuts.
There is a difference between the two: In the case of HttpResponseRedirect the first argument can only be a url . redirect which will ultimately return a HttpResponseRedirect can accept a model , view , or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.
The render function Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. You request a page and the render function returns it. The redirect function sends another request to the given url.
I do this all the time, no need for a session object. It is a very common pattern POST-redirect-GET. Typically what I do is:
This way you save upon POST and redirect after saving.
An example view, assuming a model of thingies:
def all_thingies(request, **kwargs):
if request.POST:
form = ThingieForm(request.POST)
if form.is_valid():
thingie = form.save()
return HttpResponseRedirect(thingie.get_absolute_url())
else:
form = ThingieForm()
return object_list(request,
queryset = Thingie.objects.all().order_by('-id'),
template_name = 'app/thingie-list.html',
extra_context = { 'form': form },
paginate_by = 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With