Django Page Redirection

22.04.2025
29

How to navigate, redirect and switch between pages on a Python-based website using Django? You can easily redirect pages with the very useful Django Library. You can do Django page redirection with two different methods as Dynamic and Static.

Django Page Redirection

Using Django Page Redirection methods, you can switch between web pages created in Python in a very fast and optimized way. All you need is a bit of Python knowledge and some knowledge of the Django library.

GitHub Project Link for Django:
https://github.com/omersahintr/WebApps

If you want to have a look, here is a link to our page about the installation and initialization of the Django Library.

Django Routing Types

Static Django Page Redirects

Now let’s try to briefly discuss how to do multiple in-site page redirects in Django.

  1. Cisco Course
  2. Python Course

Let’s have two courses on our site. Let’s make dynamic URL redirection for both courses according to this scenario. Let’s open the project/views.py file and add the following lines.

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("First Django Project Test OK.")

def cisco_course(request):
    return HttpResponse("Network Cisco Course")

def python_course(request):
    return HttpResponse("Python Course")
Project/views.py

After these definitions, let’s make changes in urls.py under the application.

from django.urls import path
from . import views

urlpatterns = [
    path("",views.index, name="index"), ## url:index 
    ##path("contacts",views.index, name="index") ## url:/contacts

    path("cisco/", views.cisco_course, name="cisco"),
    path("python/", views.python_course, name="Python")
    
]
App/urls.py

Then let’s activate the server by running ” python manage.py runserver 8080” command in Terminal. In the web browser, type http://127.0.0.1:8080/chat_message_app/python/ and run it.

Screen Shot:

Likewise, when we type http://127.0.0.1:8080/chat_message_app/cisco/, the Django Page Redirection process runs and produces the following result;

you will see the screens.

Dynamic Routing with Python Django

Let’s have a dictionary, Json or page data from a data file. How can we dynamically add them to the project in Django in one line?

Let’s start by defining a Dictionary. Let’s avoid confusion with dynamic routing by defining the page data in this dict in a single line respectively.

from django.shortcuts import render
from django.http import HttpResponse

course_dict = {
    "python":"Welcome to Python Course",
    "cisco":"Welcome to Cisco Course",
    "java":"Java Course",
    "charp":"C# Course",
    "swift":"Swift Course"
}

def index(request):
    return HttpResponse("First Django Project Test OK.")


def course(request, userurl): #user_url: user browser written url.
    return HttpResponse(course_dict.get(userurl,"Page is Not Found - 404"))
Project/views.py

On the urls.py side, we need to get the page name to be written at the end of the url with a parameter. For this, we can specify the parameter and data type to be taken in “<str:user_url>/” when defining the path. If the user_url here and the name you give for the parameter in views are the same, you will avoid confusion.

from django.urls import path
from . import views

urlpatterns = [
    path("",views.index, name="index"), ## url:index
    path("<str:userurl>/", views.course, name="course")
    
]
App/urls.py

Screenshot:

django page redirection

Multiple Integer Type Parameter Extraction

Let’s pull more than one integer type data from the browser address line with Django, do mathematical exponentiation with these numbers and print them on the screen. Let’s call the first number n1 and the second number n2 to be written at the end of the URL. Let’s do this in views.py:

from django.shortcuts import render
from django.http import HttpResponse


def pow_view(request,n1,n2):
    return HttpResponse(f"{n1}^{n2}={pow(n1,n2)}")
Project/views.py

in app/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path("",views.index, name="index"), ## url:indlocalhost/app/
    path("<int:n1>/<int:n2>/",views.pow_view,name="pow") ## url:localhost/app/2/8/
    
]
App/urls.py

Screenshot:

Managing 404 Page Not Found Error with Django

One of the most important features of Django Page Redirection is the management of error pages. So for a wrong url typed by the user in the address line, we will redirect to a 404-Page Not Found page and even take a look at the design of this error page.

There is a very easy way, but first we need to add the Http404 sub-library to views.py.

from django.shortcuts import render
from django.http import HttpResponse, Http404


def course(request,userurl):
    try:
        course = course_dict[userurl]
        return HttpResponse(course)
    except:
        raise Http404("404 - This page is not found!")
Project/views.py

In the app/urls.py file;

from django.urls import path
from . import views

urlpatterns = [
    path("",views.index, name="index"), ## url:indlocalhost/app/
    path("<str:userurl>/", views.course, name="course") ## url:localhost/app/cisco/
    
]
App/urls.py

Screenshot:

Turning Django Debug Mode On and Off

In the red frame in the picture above, you can see the error message that we set. This page is shown in detailed “debug” mode so that only the designer and developer can see it.

When development is finished, it can be turned off with a modification to Project/settings.py.

Debug Mode Activation

By changing the “DEBUG=True” parameter between lines 20-30 of the Settings.py file, the detailed Django error page display can be turned on or off.

django sayfa yönlendirme

Debug Mode Shutdown

If you set Debug=False, the detail information on the error pages will be hidden from the users. However, when you do this, you need to assign a string value as ALLOWED_HOSTS = [“localhost”] or ALLOWED_HOSTS = [“127.0.0.1”] to the ALLOWED_HOSTS section on the bottom line.

If you type 127.0.0.0.1 after turning Debug mode False and Allowed Hosts to “localhost“, the server will return an error page as Bad Request (400).

When you type localhost in the browser for the server name, if you call a page that does not exist, a simpler error page will be shown as below.

We can also change the design of this error page. For this we will add a return line under except in the Try-Except block in views.py. It will also be necessary to include the HttpResponseNotFound module in the project before doing this.

Project/views.py :

from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseNotFound


def course(request,userurl):
    try:
        course = course_dict[userurl]
        return HttpResponse(course)
    except:
        return HttpResponseNotFound("404-Not Found Error!!!")
Project/views.py

When we save the file and refresh the page, the following error page will be shown for the page not found:

page redirection django

Permalink Redirect Process

In order to redirect the url of a page that will be unpublished to a different page or to create internal links with the use of ID, we may need to perform Redirection in Django. For this we will use the HttpResponseRedirect module.

from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseNotFound, HttpResponseRedirect

course_dict = {
    "python":"Welcome to Python Course",
    "cisco":"Welcome to Cisco Course",
    "java":"Java Course",
    "charp":"C# Course",
    "swift":"Swift Course"
}
    
def course_select(request,n1): ##localhost/1/ --> localhost/swift/
    if n1 == 1:
        return HttpResponseRedirect("swift")
    else:
        return HttpResponseNotFound("This page not found!")
Project/views.py

App/urls.py :

from django.urls import path
from . import views

urlpatterns = [

    path("<int:n1>",views.course_select,name="course_select")
    
]
App/urls.py

As a result, when we call our localhost/app/1/ page from the browser, it will automatically redirect to localhost/app/swift/ with Http-301 permalink redirection;

This method is not used much, it can be used locally and temporarily in the escape tabs in between. Instead, the Reversing method is preferred, where we use the “name” parameters.

Django Connection Reversing

Using the name parameters we defined in urls.py, we can make a more useful page redirection process. For this we need to add the module “from django.urls import reverse” in views.py.

from django.urls import path
from . import views

urlpatterns = [
    
    path("",views.index, name="index"), ## url:indlocalhost/app/
    path("<int:n1>",views.course_select,name="course_select"),
    path("<str:userurl>/", views.course, name="course"), ## url:localhost/app/cisco/
    
]
App/urls.py

Project/views.py :

from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseNotFound, HttpResponseRedirect
from django.urls import reverse

course_dict = {
    "python":"Welcome to Python Course",
    "cisco":"Welcome to Cisco Course",
    "java":"Java Course",
    "charp":"C# Course",
    "swift":"Swift Course"
}

    
def course_select(request,n1): ##localhost/1/ --> localhost/cisco/
    course_list = list(course_dict.keys()) ##get dictionary id's
    try:
        course = course_list[n1]
        page = reverse("course", args=[course]) ##select urls.py paths name parameters
        
        return HttpResponseRedirect(page)
    except:
        raise Http404("404 - This page is not found!")
Project/views.py

When we type localhost/app/0/ in the web browser, our page will automatically redirect to the python course page:

This is the most professional way of link forwarding in Django. This is why Name parameters have become important.

MAKE A COMMENT
COMMENTS - 0 COMMENTS

No comments yet.

Bu web sitesi, bilgisayarınıza bilgi depolamak amacıyla bazı tanımlama bilgilerini kullanabilir.
Bu bilgilerin bir kısmı sitenin çalışmasında esas rolü üstlenirken bir kısmı ise kullanıcı deneyimlerinin iyileştirilmesine ve geliştirilmesine yardımcı olur.
Sitemize ilk girişinizde vermiş olduğunuz çerez onayı ile bu tanımlama bilgilerinin yerleştirilmesine izin vermiş olursunuz.
Çerez bilgilerinizi güncellemek için ekranın sol alt köşesinde bulunan mavi kurabiye logosuna tıklamanız yeterli. Kişisel Verilerin Korunması,
Gizlilik Politikası ve Çerez (Cookie) Kullanımı İlkeleri hakkında detaylı bilgi için KVKK&GDPR sayfamızı inceleyiniz.
| omersahin.com.tr |
Copyright | 2007-2025