Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - passing information when redirecting after POST

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?

like image 641
Acorn Avatar asked Feb 06 '11 10:02

Acorn


People also ask

Can we pass data with redirect in Django?

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.

What is the difference between HttpResponseRedirect and redirect?

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.

What is the difference between render and redirect in Django?

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.


1 Answers

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:

  1. Have a view with object list and a form to post data
  2. Posting successfully to that form saves the data and generates a redirect to the object detail view

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)
like image 131
Carles Barrobés Avatar answered Oct 04 '22 01:10

Carles Barrobés