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



Python


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

So many times, on your website, once a user creates a post, you would to then redirect a user to that newly created page.

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

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

So how can this be done in Django?

How can we take a user from a create page, where a user has just created 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, createpost, which renders the create 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 creates 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 created.

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


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...