Updated May 29, 2023
Introduction to Django redirect
We know that Django provides different kinds of functionality to the user; here, a redirect is one of the functionalities that Django provides. For example, when we create a Python web-based application by using the Django framework, so at some point, we need to redirect one URL to another URL; in another situation, suppose we need to perform a specific action, or any error may occur at that time we need to redirect the page to another page at that time we can use the redirect method to achieve the same. Django provides two types of redirects such as temporary and permanent redirects.
What is Django redirect?
Page redirection is required for some reason in web applications. It would help if you diverted a client to another page when a particular activity happens or in case of a mistake. For example, when a client signs in to your site, the system often redirects them to the relevant landing page or their dashboard. You can achieve redirection in Django by utilizing the ‘redirect’ method. Whenever we make a web application using the Django system, we eventually find where we want to visit from one URL to another. From our view in Django, we can undoubtedly bounce from the current URL to one more URL by returning an occasion of HttpResponseRedirect or HttpResponseRedirect. We want to import the divert work utilizing the Django.shortcuts module in our view.py record.
When you attempt to get to a page of Django administrator without validation, it diverts you to the sign-in page. There, inputting the proper accreditations redirects you to a similar page you need to access before the sign-in page. This redirection cutoff points to the Django Admin and more tasks like adding new articles in models through the administrator, changing passwords, and more. Page Redirection is a significant consideration in giving the client an incredible experience. An engineer will take full advantage of this component of Django.
Why Use Django redirect?
Now let’s see the use of redirecting in Django:
- Suppose a user is not logged in, and the requested URL requires authentication to redirect to the login page.
- When the user logs in successfully, Django redirects and transfers user requests to the original request.
- Sometimes we need to change the password; then, we need to show a message that the password was changed successfully, so we need to redirect to this page for that purpose.
- When you attempt to get to a web-based entertainment page where you need to message or like the post, the server diverts you to the login page on the off chance that you haven’t done that.
- Not just that, but a few decent designers had made the framework to reach the page you previously needed to access when you signed in/join.
- When playing out some effective procedure on the site, such as changing your secret phrase, the site should divert you to a page showing the activity’s effectiveness.
How to Add Django redirect work?
Now let’s see how we can add redirects into Django as follows:
First, we need to create the virtual environment for our application with the help of the below command as follows:
Code:
mkdir sample_auth
cd sample_auth
python –m venv env
source env/bin/activate
pip install django
We need to create an application inside the project, open the setting .py file, and add the created application to the list.
Code:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'samplapp',
]
Now create the model; if our project is complex, then we need to create a different model inside the project, and it can be handled only by using authentication. So inside the samplapp, we need to add the model as follows.
Code:
from django.db import models
Here we need to send the token to Django for mode, so we need to add the following line inside the setting file.
Code:
Student_model= 'samplapp.student'
After that, we must migrate and register the created model inside the admin dashboard, as shown in the code below.
Code:
from .models import Student
admin.site.register(Student, StudentAdmin)
Demands are dependably HTTP Requests, yet there can be various Responses like we returned HttpResponse in our first views.py.
We will return a HttpResponseRedirect case or class object to divert the user. You want to compose divert instead of rendering it in the perspectives document. We should alter views.py documents.
Here we need to add the required packages, but before that, we must ensure that another URL we kept inside the URL file. Inside the view, the file adds the following package as follows.
Code:
from django.shortcuts import render, redirect
from django.http import HttpResponse
After that, we must create the function and write the following code.
Code:
def home(request):
return HttpResponse("<h1>Hi Welcome</h1>Configuration of is done")
def about(request):
return redirect('/about')
Now we need to open the url file and add the following code.
Code:
from django.contrib import admin
from django.urls import path, include
from .views import *
urls = [
path('admin/', admin.site.urls),
path('redirect/', about),
path('about/', home),
]
Django redirect function
Let’s see what the redirect function is with an example as follows:
This redirect function is equipped for taking something beyond URLs; you can divert your clients to models or divert to a specific URL while passing the critical qualities and other required data. In any case, work-based diverts are generally simple to utilize and are adequate.
Now let’s see an example for better understanding as follows:
Code:
from django.shortcuts import render, redirect
from django.http import HttpResponse
import datetime
def home(request):
day = datetime.datetime.now().date()
return redirect("https://www.sampleproject.com")
def about(request, studId):
return redirect(studdetails, studId = "020", name = "Jenny")
def about (request, syudId, name):
t = "Stduent ID and Name from another URL : %s : %s"%(studId, name)
return HttpResponse(t)
Explanation:
First, we need to import the different packages as per our requirements. First, we redirect to the home page so that the URL specified in the above code is shown. After accessing our created application, we were redirected to the home page, as shown below.
After accessing the student id, we can see the result in the screenshot below.
In the above example, we can also specify the temporary and permanent URLs as per our requirement, so for that purpose, we need to add this parameter inside the view file. There is likewise a capacity to create URLs; it is utilized similarly as divert, the ‘opposite’ strategy. This capacity doesn’t return a HttpResponseRedirect object; however, just a string containing the URL to the view incorporated with any passed contention.
Conclusion
With the help of the above article, we saw about the Django redirect. From this article, we saw basic things about the Django redirect, the features and installation of the Django redirect, and how we use it in the Django redirect.
Recommended Articles
We hope that this EDUCBA information on the “Django redirect” was beneficial to you. You can view EDUCBA’s recommended articles for more information.