How to Redirect a User From a Update View to a Detail View in Django



Python


In this article, we show how to redirect a user from an update view to a detail view in Django.

So many times, on your website, when a user updates a post, you would want to then redirect the user to that newly updated page.

That newly updated page is the detail page of that post.

So what you want to do is redirect a user from the update view to the detail view.

So how can this be done in Django?

How can we take a user from an update page, where a user has just updated a post, and bring him/her to the detail page?

It turns out we can use the HttpResponseRedirect() function and pass in a placeholder and then use the format() function and pass in the value we want.

We show this below in the views.py file.



So we have the function, editpost, which renders the update post page of our website.

Our detail page for each is at the URL, /posts/postid/, where postid is the id of the post we are redirecting to.

So to create this dynamic url and redirect the user to this detail page, we use the HttpResponseRedirect and manually construct the URL, which is, "/posts/{id}/".format(id= post.id)

{id} is a placeholder and we use Python's format() function to specify the value of id.

Now when the user successfully updates a post, s/he is redirected to the detail page of the post, so that s/he can see how his/her posts looks once updated.

And this is how we can redirect a user from an update view to a detail view in Django automatically once the post is updated.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...