django - passing information when redirecting after POST

4.8k Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

You can:

  1. Pass the data (either full data or just id to object) in request.session
  2. Redirect with something like ?id=[id] in URL - where [id] points to your object.

Update:

Regarding pt. 1 above, I meant that you could do (in POST handler):

my_object = MyModel.objects.create(...)
request.session['my_object_id'] = my_object.id

Or you could try passing the whole object (it should work but I'm not 100% certain):

my_object = MyModel.objects.create(...)
request.session['my_object'] = my_object
5
On

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)