Redirects in Django

Django redirects are the mechanism we have to send from one page to another that we have configured in our Django app; redirects are nothing more than the behavior of sending a client or user to another page, either from our application or from another application; For SEO, the 302 code is usually used to do this type of operation; a common example of redirects is when we have a post or publication in which we change the title and with it the slug but we don't want to lose the positioning of the original post, in these cases, we can do a 302 type redirect to the new link.

 

Redirects are a common behavior that when -for example- we send a request to create a record, this function may not have a template associated, due to its purpose; therefore what we do are redirects:

  1. If the data is correct, we make a redirection to the list, creation or update form.
    If the data has problems with the validations we send it to the creation page

So, for the following routes:

app_name="gestion"
urlpatterns = [
   path('',views.index, name="index"),
   path('detail/<int:pk>',views.show, name="show"),
   path('create',views.create, name="create"),
   path('update/<int:pk>',views.update, name="update"),
   path('delete/<int:pk>',views.delete, name="delete")
]

And if we want to do a redirection:

return redirect('gestion:index')

We redirect indicating the name of the app, followed by a colon, followed by the name of the route.

Example creation function:

def create(request):
   form = ProductForm()
   if request.method == "POST":
       form = ProductForm(request.POST)
       if form.is_valid():
           product = Product()
           product.title = form.cleaned_data['title']
           product.price = form.cleaned_data['price']
           product.description = form.cleaned_data['description']
           product.category = form.cleaned_data['category']
           product.save()
           return redirect('gestion:update', pk=product.id)
       else:
           print("Invalido")

As you can see, in this view we load a default template, but based on logic (correct data received) we redirect to the update view.

Django return redirect() with parameters

It is also possible to redirect with parameters;

return redirect('update', pk=15)

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.