How to get the path name of an URL in view?

Question:

I have urls paths with name in my urls.py file.

urls.py

urlpatterns = [
    path('home/', views.home, name="home_view"),
]

my views.py

def home(request):
    path_name = get_path_name(request.path)
    return HttpResponse(path_name)

Now, I need to get the path name, "home_view" in the HttpResponse.

How can I make my custom function, get_path_name() to return the path_name by taking request.path as argument?

Asked By: rangarajan

||

Answers:

You can use request.resolver_match.view_name to get the name of current view.

def home(request):
    path_name = request.resolver_match.view_name
    return HttpResponse(path_name)
Answered By: Sunderam Dubey

from django.urls import path
from . import views

app_name = 'polls'

urlpatterns = [path('', views.index, name='index')]

print(urlpatterns[0]) # Output: <URLPattern '' [name='index']>
print(f"name is: {urlpatterns[0].name}") # Output: name is: index

So the URL leads to /
And the name is "index"

Answered By: Omar Magdy

You can check this documentation provided by Django to backtrace the URL calling the view.

https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpRequest.resolver_match

There is also a link in that documentation which shows capturing/logging the exception if you are looking for that.
https://docs.djangoproject.com/en/4.0/topics/http/middleware/#process_view

Answered By: Zaman Afzal