'Django. How to get URL by its name?

I want to get url by name specified in urls.py.

Like {% url 'some_name' %} in template, but in Python.

My urls.py:

urlpatterns = [
    ...
    path('admin_section/transactions/', AdminTransactionsView.as_view(), name='admin_transactions'),
    ...
]

I want to something like:

Input: url('admin_transactions')
Output: '/admin_section/transactions/'

I know about django.urls.reverse function, but its argument must be View, not url name



Solution 1:[1]

Django has the reverse() utility function for this.

Example from the docs:

given the following url:

from news import views

path('archive/', views.archive, name='news-archive')

you can use the following to reverse the URL:

from django.urls import reverse

reverse('news-archive')

The documentation goes further into function's use, so I suggest reading it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chillie