[Solved]-Using urls names in views



Check out the docs on reverse

They have a specific example reversing a named url here:


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]))


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:


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

    def get_queryset(self):
       name = self.request.resolver_match.url_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.


    var salesApiUrl = "{% url 'URLNamesHere' %}"

Now, the salesApiUrl is global. You can use the var name in js as well

Leave a comment