Using urls names in views

I know this topic is years old, however during my own search for the same, this one popped up. I believe the requester is looking for the following in views.py:

views.py

class Overview(ListView):
    model = models.data
    template_name = "overview.html"

    def get_queryset(self):
       name = self.request.resolver_match.url_name
       print(name)

Do note that I'm using class based views. Within regular views, the name can be retrieved as follows (not tested):

def current_url_name(request):
    html = "<html><body>Url name is {}.</body></html>".format(request.resolver_match.url_name)
    return HttpResponse(html)

The url name is within the (self.)'request' variable. From within your view, 'resolver_match.url_name' is the one you're looking for.

Hope this helps people in search of the same.


https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

(Updated answer to point to an existing url.)


Check out the docs on reverse

They have a specific example reversing a named url here:

https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

viewname is either the function name (either a function reference, or the string version of the name, if you used that form in urlpatterns) or the URL pattern name.

def myview(request):
    return HttpResponseRedirect(reverse('arch-summary', args=[1945]))