Home >>Django Tutorial >Django Page Redirection

Django Page Redirection

Django Page Redirection

Page redirection is used in a web application for many reasons like redirecting a user to another page when a specific action occurs, or basically in case of error. In Django, we have the 'redirect' method for the page redirection.

The 'redirect' method takes the URL to be redirected as an argument.

The myapp/views will look like this:


def hello(request):
   today = datetime.datetime.now().date()
   days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "example.html", {"today" : today, "days_of_week" : days})

Now, Let's change the hello view to redirect to the phptpoint.com. So the myapp/view.py will look like:


from django.shortcuts import render, redirect
from django.http import HttpResponse
import datetime

# Create your views here.
def hello(request):
   today = datetime.datetime.now().date()
   days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return redirect("https://www.phptpoint.com")

In the above example, first, we import the redirect from django.shortcuts, and for redirection, we just pass the full URL to the 'redirect' method as a string.

It is also possible to define whether the 'redirect' is temporary or permanent by adding permanent = True parameter. The user will not see any difference but the search engines will take this into account when ranking our website.


No Sidebar ads