rangarajan
rangarajan

Reputation: 191

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

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?

Upvotes: 3

Views: 1594

Answers (2)

Omar Magdy
Omar Magdy

Reputation: 3313

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"

Upvotes: 0

Sunderam Dubey
Sunderam Dubey

Reputation: 8837

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)

Upvotes: 3

Related Questions