Reputation: 6756
Is it possible to use urls names in views, like we can do it in template?
Upvotes: 14
Views: 10094
Reputation: 436
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.
Upvotes: 3
Reputation: 1191
<script>
var salesApiUrl = "{% url 'URLNamesHere' %}"
</script>
Now, the salesApiUrl is global. You can use the var name in js as well
Upvotes: 0
Reputation: 599610
https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls
(Updated answer to point to an existing url.)
Upvotes: 2
Reputation: 118458
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]))
Upvotes: 13