How to use Redirect in Python Django?

Published On: 19/09/2022 | Category: Django


Hi Dev,

This article is focused on how to use redirect in django. I’m going to show you about how to use return redirect in django. if you have question about how to use redirect function in django then I will give simple example with solution. Here you will learn django url redirect to another url.

Django function redirect will basically return an HttpResponseRedirect with the proper URL. I think you always prefer to use this shortcut so my code base remains consistent.

So, main benefits using redirect instead of HttpResponseRedirect is that you can pass different types of arguments and also it will save you from importing django.urlresolvers.reverse in your django project in your views.py file

Here i explained simply step by step example of how to use redirect in django.

There are three arguments in redirect method:

  1. Model Instance: This will call the model’s get_absolute_url() method
  2. Reverse URL Name: accept view arguments..
  3. An Absolute or Relative URL:

Model Instance

In this arguments, This will call the model’s get_absolute_url() method;

from django.shortcuts import redirect
from simple_blog.models import Blog

def post_view(request, post_id):
    blog = Blog.objects.get(pk=post_id)
    return redirect(blog)

This is a similar to: return HttpResponseRedirect(blog.get_absolute_url())

Reverse URL Name:

In this arguments, This will call the reverse url name accepting the view arguments

from django.shortcuts import redirect
from simple_blog.models import Blog

def post_view(request, post_id):
    return redirect('post_details', id=post_id)

This is a similar to: return HttpResponseRedirect(reverse('post_details', args=(post_id, )))

Absolute or Relative URL:

In this last arguments, this will call the absolute or relative url in view arguments:

from django.shortcuts import redirect

def relative_url_view(request):
    return redirect('/blog/cat/django/')

def absolute_url_view(request):
    return redirect('https://tuts-station.com/blog/cat/django/')

Relative URL: this is a similar to return HttpResponseRedirect('/blog/cat/django/')

Absolute URL: this is a similar to return HttpResponseRedirect('https://tuts-station.com/blog/cat/django/')

I hope it will help you....

Happy Coding!