Table of contents
1.
Introduction
2.
What is Django Redirect?
3.
How is Django Redirect Useful?
3.1.
Example
3.2.
Python
3.3.
HTML
3.4.
HTML
3.5.
Python
3.6.
Python
3.7.
Python
3.8.
HTML
4.
Frequently Asked Questions
4.1.
What is Django?
4.2.
What do you mean by Django Redirect?
4.3.
How do redirections between web pages help the user?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Django Redirect

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django is a high-level Python framework. It allows you to develop fast and robust websites even driven by complex databases. It enables hassle-free website development, which has made it famous. Big tech giants like Instagram, Spotify, YouTube, etc, use it. And, when we talk about a website, it can contain more than one webpage. Thus, switching between those pages on specific points is essential when programming a website.

Django Redirect

In this article, we will study Django Redirects.

What is Django Redirect?

Django Redirect redirects the user from one webpage to another upon some event. This event can be precisely defined, or it can be an error. The most common example is when a user logs into some website, they are redirected to the dashboard or the home page.

In Django, the parameter passed to the redirect function is the webpage URL to which it will redirect the user. Let us understand this with a simple example of the submission of a form.

But first, if you are new to Django, you should read Introduction to Django Framework.

Also, use the following command to install Django on your system.

pip install django
You can also try this code with Online Python Compiler
Run Code

 

Then, create a folder for your Django project, open its path in your terminal, and write the following code to create a folder for your Django project with your desired name.

django-admin startproject <project_name>
You can also try this code with Online Python Compiler
Run Code

 

Then, you will see a folder with your entered name made in the folder with some .py files for the Django project. You can use the following command in your folder’s location in the terminal to locally run the project.

python manage.py runserver 4444
You can also try this code with Online Python Compiler
Run Code

 

Here, we have written 4444 to specify the local host port number. You can write a port number of your choice.

OUTPUT

django project created

How is Django Redirect Useful?

Django redirect is helpful for many scenarios. Let us see some examples of it:

  • If some user is not logged in and tries to go to the webpage using a URL that requires authentication, it can block the user from doing so.
     
  • If users log in successfully, we can redirect them to the required page.
     
  • If some user changes their password, a redirect can show them that the password has been changed successfully.
     
  • It provides directions to the user to use the application wisely.

Example

We have created a templates folder for our HTML files and views.py file in our folder.

  • Python

Python

from django.contrib import admin
from django.urls import path
from sample import views

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', views.homepage),
   path('about-me/', views.aboutme),
   path('content/', views.content),
   path('userform/', views.formm),
   path('contents/<contentid>', views.contentdetails)
]
You can also try this code with Online Python Compiler
Run Code

The following code is of our urls.py file:

We have specified different urls for different webpages.

Next, we have our index.html file for our homepage as follows:

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>{{title}}</title>
</head>
<body>
   Welcome to CODING NINJAS!<br>
   Hello
   </body>
</html>

Next, we have our userform.html file for our form to be filled for this example, with two entries to be taken and a submit button.

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>UserForm</title>
</head>
<body>
   <div class="row">
       <div class="col-12">
           <form method="post">
               {% csrf_token %}
               <div for="">Entry 1</div>
               <input type="text" name="nm" class="form-control">
               <div for="">Entry 2</div>
               <input type="text" name="nm1" class="form-control">
               <div>
                   <button type="submit">SUBMIT</button>
               </div>
           </form>
       </div>
   </div>
</body>
</html>

 

Here, the csrf_token generates a random token every time the page loads to prevent attacks on the page and secure it.

Next, we have written our views.py in the following manner:

  • Python

Python

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
def aboutme(req):
   return render(req, "aboutt.html")

def content(req):
   return HttpResponse("Different Contents")

def contentdetails(req, contentid):
   return HttpResponse(contentid)

def homepage(req):
   return render(req, "index.html")

def formm(req):
   data={}
   try:
       if req.method=="POST":
           n=req.POST.get('nm')
           n1=req.POST.get('nm1')
           data={
               'n1':n,
               'n2':n1,
               'output':n+n1
           }
           return HttpResponseRedirect('/')
   except:
       pass
   return render(req, "userform.html", data)
You can also try this code with Online Python Compiler
Run Code

We have imported HttpResponseRedirect for using the redirecting option.

The fromm function redirects the user to the URL of our homepage, which we have seen in our urls.py file. It uses the req.POST.get() function to get the two values we have taken from the user when he/she has filled out the form. Then, we store it in data as two different values and one more for their concatenation. Then, we redirect the user to the homepage of the website.

So, after running the server and going to the URL as follows, we should fill out a form and submit it to be redirected to the home page.

URL=http://localhost:8000/userform/
 

OUTPUT

form entry

Next, after we submit it, it redirects us to the home page.

redirected output

It is the process of redirection that we have achieved. We can also edit some of our codes to get the concatenated value of our responses on the homepage.

The homepage in the view.py file is edited as follows:

  • Python

Python

def homepage(req):
   if req.method=="GET":
       output=req.GET.get('output')
   return render(req, "index.html", {'output':output})
You can also try this code with Online Python Compiler
Run Code

We have created an output that takes the values for the index.html file.

Next, formm function is edited as below:

  • Python

Python

def formm(req):
   data={}
   try:
       if req.method=="POST":
           n=req.POST.get('nm')
           n1=req.POST.get('nm1')
           data={
               'n1':n,
               'n2':n1,
               'output':n+n1
           }

           urltemp="/?output={}".format(n+n1)

           return HttpResponseRedirect(urltemp)
   except:
       pass
   return render(req, "userform.html", data)
You can also try this code with Online Python Compiler
Run Code

Now, we redirect to a defined URL with the URL of the homepage combined with the concatenated values of our responses.

Next, our index.html file is edited as below:

  • HTML

HTML

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>{{title}}</title>
</head>
<body>
   Welcome to CODING NINJAS!<br>
   Hello {{output}}
</body>
</html>

Here, the {{output}} denotes the passed value to it, which we coded in our views.py file in the homepage function.

When we enter the values in our form, they are also passed to the redirected page.

OUTPUT

output form
output redirected

 

Thus, we can achieve different results using Django Redirects to our requirements. Now, there are two types of Django redirect: temporary and permanent. The permanent one makes permanent changes to the URL. Both of these are for search engine optimization.

Frequently Asked Questions

What is Django?

Django is a high-level Python framework. It allows you to develop fast and robust websites even driven by complex databases. It enables hassle-free website development, which has made it famous. Big tech giants like Instagram, Spotify, YouTube, etc, use it.

What do you mean by Django Redirect?

Django Redirect redirects the user from one webpage to another upon some event. This event can be precisely defined, or it can be an error. The most common example is submitting a form and getting redirected to a different page.

How do redirections between web pages help the user?

It helps the user navigate smoothly through different web pages on the website. Also, performing operations on the application may lead to some inconveniences, and sometimes redirects prevent accidental operations from happening twice.

Conclusion

Django is a high-level and famous Python framework for building web applications. In this article, we specifically studied Django Redirect. We looked into its definition, Django’s installation, and its uses. Then, we learned it with the help of an example and saw the working with different cases.

If you are interested in learning more about this topic, read the following articles:-

 

To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Codestudio. Also, you can enroll in our courses and check out the mock test and problems available. Please check out our interview experiences and interview bundle for placement preparations.

 

Happy Coding!

Live masterclass