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 the future. It may create many issues in the future when there are any changes to the url’s 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. 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 with the redirect variable. Next, the actual reverse function is used. The actual reverse function is used for performing the reverse happens. 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 be for the redirect url name from the url’s.py file.
How does the reverse function work in Django?
The reverse function can be considered very useful in url handling. It helps 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 reverses 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 function
1. Changes in url.py file
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 returning the actual url value in place. We can notice from the below example that each of the urls declared is associated with a url value, 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//',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. This redirect is achieved using the reverse function.
Conclusion
The above article mentions the use of the Django reverse function, how the reverse function can be used in Django to avoid hardcoding URLs, and suitable examples to explain the use and execution of the reverse function in Django.