Updated May 20, 2023
Introduction to Django Reverse
Usually, all web applications involve a huge amount of urls in them. Based on the web application, the number of URLs can be thousands or even lakhs. With these many pages deployed, hardcoding the URLs in each page, view, or every template involved may become very hectic in the future. It may create many issues in the future when there are any changes to the URLs used. To overcome this, the reverse function can be used. The reverse function allows retrieving url details from the url’s.py file through the name value provided. This is the primary use of the reverse function in Django.
Syntax:
from django.urls import reverse
Redirect_Variable = reverse(redirect_url_name)
The redirect variable is the variable here that will have the reversed value. We assign the reversed URL value here. The backend allocates the URL value for the specified name in redirect_url_name and associates it with the redirect variable. We then use the actual reverse function to perform the reverse operation. This method is responsible for retrieving the new URL value in reverse. With the reverse function, the redirect url name must be specified. The name of url value specified here will be for the redirect url name from the url’s.py file.
How does the reverse function work in Django?
The reverse function is highly useful in URL handling. It helps avoid any future breakdown in the application because of its capability to hold url values in it. The reverse function can be divided into three straightforward methods:
1) Declare the url to be framed in the url’s.py file. This is the most critical section. All future references of the url will happen from here only.
2) Next, from the url’s.py file, go to the view, and in the new view, the reverse function has to be declared with the variable name of the url hardcoded in it. This section reverses the url field name into a valid url value.
3) The last section involves the actual redirect. In this section, the code triggers and processes the redirect. When this section is called, it redirects the user to the specified page.
Create a DJANGO reverse function
1. Changes in url.py file
Below is the URL’s file. In the urls.py file, you can declare all the URLs for your Django project. Each URL is assigned a name using the name argument. This name argument calls the reverse function and returns the actual url value in place. In the example provided, it is evident that each declared URL is associated with a URL value, which activates a reverse-based storage operation in the backend.
url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'Jsoncheck/',views.Json_Response,name='Json_Response'),
url(r'^$',views.Entry_page,name='Entry_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'all/',views.All_users,name='all'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_Call, name="register"),
url(r"login/", views.login_Call, name="login"),
path(r'profile//',views.profile_page,name='profile'),
url(r'logout/',views.logout_Call,name='logout'),
url(r'reg/',views.profile_reg_user,name='reg'),
path(r'update//',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.M
2. Create a view for the form
The integer value, when submitted, has to be stored, and when retrieved, it has to be pulled from the database. This can be achieved using the object created for the model. The process of doing this is explained in the below-given views.py section.
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import NewUserForm,Valueform
from django.contrib.auth import login,authenticate,logout
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test,login_required
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.urls import reverse
def All_users(request):
User_entries = User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(User_entries, 5)
users = paginator.page(page)
print(" Has other pages : ",users.has_other_pages())
print(" Has next page : ",users.has_next())
print(" Has previous page : ",users.has_previous())
print(" Has previous page : ",users.has_previous())
print(" Start Index : ",users.start_index())
print(" End Index : ",users.end_index())
if users.has_next():
print(" Next page Number: ",users.next_page_number())
elif users.has_previous():
print(" Has Previous page Number: ",users.previous_page_number())
print(paginator,users)
return render(request,"All_users.html",{'users':users})
def Sign_up_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
print(form.is_valid())
if form.is_valid():
user = form.save()
login(request, user)
print(User.objects.all())
messages.success(request, "Registration successful." )
named_redirect = reverse('Welcome_page')
return redirect(named_redirect)
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm
return render (request,template_name="Signup.html", context={"Sign_up_form":form})
def login_request(request):
if request.method == "POST":
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(request,username=username, password=password)
if user is not None:
print('1',request.user.is_authenticated, request.user)
login(request, user)
# logout(request)
print('1',request.user.is_authenticated, request.user)
messages.info(request, f"You are now logged in as {username}.")
named_redirect = reverse('Welcome_page')
return redirect(named_redirect)
else:
messages.error(request,"Invalid username or password.")
form = AuthenticationForm()
return render(request=request, template_name="login.html", context={"login_form":form})
def logout_request(request):
if request.user.is_authenticated:
logout(request)
print('2',request.user.is_authenticated, request.user)
messages.info(request, "Logged out successfully!")
named_redirect = reverse('Welcome_page')
return redirect(named_redirect)
@login_required
def Reverse_Redirect_Example_page(request,pk):
render_dict2 = {}
Key_details = Bride.objects.get(id=pk)
Reverse_Redirect_Example_name = Key_details.name
Reverse_Redirect_Example_Age = Key_details.age
Reverse_Redirect_Example_Thegai = Key_details.thegai
Reverse_Redirect_Example_state = Key_details.State
Reverse_Redirect_Example_district = Key_details.District
Reverse_Redirect_Example_Address = Key_details.Address
Reverse_Redirect_Example_Phone = Key_details.Phone
Reverse_Redirect_Example_Profession = Key_details.profession
Reverse_Redirect_Example_Salary = Key_details.salary
Reverse_Redirect_Example_UG = Key_details.Under_Graduation_Degree
Reverse_Redirect_Example_UGC = Key_details.Under_Graduation_college
Reverse_Redirect_Example_PG = Key_details.Post_Graduation_Degree
Reverse_Redirect_Example_PGC = Key_details.Post_Graduation_college
Reverse_Redirect_Example_UG = Key_details.Under_Graduation_Degree
Reverse_Redirect_Example_UGC = Key_details.Under_Graduation_college
Reverse_Redirect_Example_PG = Key_details.Post_Graduation_Degree
Reverse_Redirect_Example_PGC = Key_details.Post_Graduation_college
Reverse_Redirect_Example_Rasi = Key_details.Rasi
Reverse_Redirect_Example_Nakshatra = Key_details.Nakshatra
render_dict2['Age'] = Reverse_Redirect_Example_Age
render_dict2['name'] = Reverse_Redirect_Example_name
render_dict2['thegai'] = Reverse_Redirect_Example_Thegai
render_dict2['State'] = Reverse_Redirect_Example_state
render_dict2['district'] = Reverse_Redirect_Example_district
render_dict2['Address'] = Reverse_Redirect_Example_Address
render_dict2['Phone'] = Reverse_Redirect_Example_Phone
render_dict2['profession'] = Reverse_Redirect_Example_Profession
render_dict2['Under_Graduation_Degree'] = Reverse_Redirect_Example_UG
render_dict2['Under_Graduation_college'] = Reverse_Redirect_Example_UGC
render_dict2['Post_Graduation_Degree'] = Reverse_Redirect_Example_PG
render_dict2['Post_Graduation_college'] = Reverse_Redirect_Example_PGC
render_dict2['Rasi'] = Reverse_Redirect_Example_Rasi
render_dict2['Nakshatra'] = Reverse_Redirect_Example_Nakshatra
print(Key_details.Creator)
print(render_dict2)
return render(request,'Profilepage.html',render_dict2)
Output:
In the below example, output clicking the login button will redirect the user to the application’s main page. We achieve this redirect using the reverse function.
Conclusion
The above article mentions the usage of the Django reverse function, which demonstrates how to avoid hardcoding URLs in Django. It provides suitable examples to explain the application and execution of the reverse function in Django.
Recommended Articles
We hope that this EDUCBA information on “Django Reverse” was beneficial to you. You can view EDUCBA’s recommended articles for more information.