Best practices to redirect user to previous page after form submit?

Hello,

in my webapp I have multiple places with “Edit” button that redirects user to form to edit particular model instance. I am currently redirecting to admin list for all the models. However what I really want is to redirect to previous page. For example:

Page A -> Form -> Submit -> Page A
Page B -> Form -> Submit -> Page B
etc

What is the correct way to do this? I think I could save the original page into session and then read it just after successful POST, but maybe there is more appropriate solution? If this could be abstracted into a decorator, that would be fantastic.

Thanks

In part, how you handle this is going to depend upon your view - the answers will change depending upon whether you’re using a function-based view, a class-based view, or one of the Django-provided Generic CBVs.

What does your view look like?

I am using FBVs. Not sure why it did not occur to me to specify this in the first post. The code is fairly straightforward, I am creating form instance from the request.POST and then seeing whether the form is valid. If so then I save the edit and redirect to the list (also FBV), if not will display the form again with errors.

There are a couple different ways that I have done this in the past.

In those cases where I have two urls pointing to the same view (one with a pk as a parameter for an edit function and one without, using that same function as a create function), I’ve done a redirect using either the get_absolute_url method on models or the reverse method passing the pk as an arg for the url.

In those cases where the view method isn’t used for a create - it’s an edit-only function for a model instance, I don’t redirect at all. Since I’m returning to the same url, I have my function return the same response for the POST as for the GET.

Ken