How to get the current url name using Django?

I don't know how long this feature has been part of Django but as the following article shows, it can be achieved as follows in the view:

   from django.core.urlresolvers import resolve
   current_url = resolve(request.path_info).url_name

If you need that in every template, writing a template request can be appropriate.

Edit: APPLYING NEW DJANGO UPDATE

Following the current Django update:

Django 1.10 (link)

Importing from the django.core.urlresolvers module is deprecated in favor of its new location, django.urls

Django 2.0 (link)

The django.core.urlresolvers module is removed in favor of its new location, django.urls.

Thus, the right way to do is like this:

from django.urls import resolve
current_url = resolve(request.path_info).url_name

As of Django 1.5, this can be accessed from the request object

current_url = request.resolver_match.url_name

If you would like the url name along with the namespace

current_url = request.resolver_match.view_name

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


For those who namespace their url patterns, then you may be interested in the namespaced url name of the request. In this case, Django called it view_name instead.

request.resolver_match.view_name

# return: <namespace>:<url name>