In this tutorial, you will learn how to redirect a user from one page to another.

Redirect using the hardcoded path in Django

# views.py 
from django.shortcuts import HttpResponse 
from django.shortcuts import redirect, reverse 
def redirect_view1(request): 
    q = request.GET.get('q') 
      if q is not None: 
          # Redirect the user 
            return redirect('/url/') # /url/ is your URL path 
        else: 
          return HttpResponse("<h1>Page 1</h1>")

Redirect using named URL's in Django

It is a two-step process - naming the URL and using this URL in the redirect(). To convert this URL name to a URL path we need to import a reverse function from django.shortcuts and pass this URL name as a parameter.

# urls.py 
from django.urls import path 
from . import views

app_name = "practice" 
urlpatterns = [ path('url1/', views.redirect_view1), path('url5/', views.redirect_view2, name="page2") ]

#views.py
from django.shortcuts import HttpResponse 
from django.shortcuts import redirect, reverse 

def redirect_view1(request): 
  q = request.GET.get('q') 
    if q is not None: # Redirect the user 
      return redirect(reverse('page2')) # page2 is the name of the URL # If you are using namespace URLs then you can write reverse('namespace_name:page2') 
    else: 
      return HttpResponse("<h1>Page 1</h1>")

Temporary Redirect in Django

A status codeĀ 302 FoundĀ indicates a temporary redirect.

from django.shortcuts import HttpResponse 
from django.shortcuts import redirect, reverse 

def redirect_view1(request): 
  q = request.GET.get('q') 
  if q is not None: 
      # Redirect the user 
        response = HttpResponse(status=302) #use status = 302 for temporary redirects 
        response['Location'] = reverse('page6') # page6 is the name of the url 
        return response 
    else: 
     return HttpResponse("<h1>Page 1</h1>")

Permanent Redirect in Django

A status codeĀ 301Ā indicates a permanent redirect.

from django.shortcuts import HttpResponse 
from django.shortcuts import redirect, reverse 

def redirect_view1(request): 
  q = request.GET.get('q') 
    if q is not None: 
      # Redirect the user 
        response = HttpResponse(status=301) #use status = 301 for permanent redirects 
        response['Location'] = reverse('page6') # page6 is the name of the url 
        return response 
    else: 
      return HttpResponse("<h1>Page 1</h1>")