How to Create a Dynamic URL in the Views.py File in Django



Python


In this article, we show how to create a dynamic URL in the views.py file in Django.

So why would you want to create a URL that is dynamic in nature in the views.py file?

There are a few reasons.

For one, in the views.py file, many times, we perform redirects.

Many times, redirects aren't just static text.

For example, performing a redirect to a detail view is something that would require a dynamic URL.

This is because the detail view URL is normally specified with the id attribute. This is because the id attribute is unique to a post. So in order to specify that post, a unique identifier such as the id attribute needs to be used.

So the URL for the detail view of a post may be, /posts/postid/, where postid is the id of the URL.

How can we construct this URL in the views.py page, so that we can perform a redirect to a dynamic URL, such as the URL for the detail view of a post?

It turns out that we can just use plain Python code to do this.

We can use placeholders and the format() function to specify the value of the placeholder.

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 create dyanmic URLs in the views.py page in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...