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

Leave a Comment