Introduction to Django Reverse
Usually, all web applications involve a huge amount of url’s in them. Based on the web application the number url’s can be thousands and even lakhs. With these many pages deployed, hardcoding the url’s in each page or each view or every template involved may become very hectic in future. It may create a lot of issues in future when there are any changes to the url’s used. to overcome this the reverse function can be used. the reverse function allows to retrieve url details from url’s.py file through the name value provided there. This is the major use of reverse function in Django.
Syntax:
from django.urls import reverse
Redirect_Variable = reverse(redirect_url_name)
The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here. So for the name of the url mentioned in the redirect_url_name, a url value will be allocated in the backend. This url value allocated in the backend will be associated to the redirect variable. Next the actual reverse function is used. the actual reverse function is used for performing the reverse happen. This method will be responsible for getting the new url value reversed. With the reverse function the name of the redirect url has to be specified. The name of url value specified here will for the redirect url name from the url’s.py file.
How reverse function works?
The reverse function can be considered very useful in url handling and it helps to avoid any future breakdown in the application because of its capability to hold url values in it. The functioning of reverse function can be divided into three straightforward methods as like below,
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 is responsible for reversing the url field name into a valid url value.
3) The last section involves the actual redirect, here the redirect will be triggered and processed. So when this section is called the redirect will happen to the page insisted.
Create a DJANGO reverse funciton
1) Changes in url.py file:
The below is the url’s file, this will be the url.py file in which all the urls be declared, these url’s are encoded with the name argument in it. This name argument is responsible for calling the reverse function and return the actual url value in place. We can notice from the below example that each of the urls declared are associated with a url value in it which triggers a reverse based store 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/<str:pk>/',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/<str:pk>/',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.M
3) 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 by means of the object created for the model. The process of doing this is explained in the below given views.py section.
Ex: 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 main page of the application. This redirect is achieved by means of reverse function.
Conclusion
The above article clearly mentions the use of Django reverse function, how the reverse function can be used in Django to avoid hardcoding of url’s and also suitable examples to explain the use and execution of reverse function in Django.
Recommended Articles
This is a guide to Django Reverse. Here we discuss the introduction, How reverse function works? examples with code implementation for better understanding. You may also have a look at the following articles to learn more –
2 Online Courses | 2 Hands-on Projects | 14+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses