Search code examples
pythondjangodjango-urlsdjango-url-reverse

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

  • 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.