Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Redirect and reverse() | Request Handling
Django: First Dive
course content

Course Content

Django: First Dive

Redirect and reverse()

Now, let's create the redirect in our post_create View function. It would be logical to redirect to the list of posts after creating a new one.

Redirection in the web refers to the process of forwarding or redirecting a user from one web page to another.

To create a redirect, we need the URL to the post_list View function. Our URL patterns:

We need the "post-list" URL pattern. App name is "NewApp". We can use the reverse() function imported from the django.urls module:

Note

The reverse() function сonverts a URL pattern to a URL address.

To use this function, we need to pass to this function following:

In this way, we will get the URL to the corresponding View. In our case is the post-list URL pattern from NewApp app:

The url variable contains the URL to the post_list View function:

Now, we can create the redirect to this URL using HttpResponseRedirect() object imported from from django.http module:

The final code of the post_create view is the following:

Now, we can create the redirection in our Views!

Note

Be careful with circular redirection, which is dangerous as an infinity loop.

1. Which function we need use to get the URL address via URL pattern?
2. Which object is used for redirection?

Which function we need use to get the URL address via URL pattern?

Select the correct answer

Which object is used for redirection?

Select the correct answer

Everything was clear?

Section 6. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt