Conteúdo do Curso
Django: First Dive
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.
Obrigado pelo seu feedback!