4

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

andrewJames
  • 19,570
  • 8
  • 19
  • 51
UselessFire
  • 53
  • 1
  • 6
  • 2
    You are mistaken about the argument. As mentioned in the [docs](https://docs.djangoproject.com/en/4.0/ref/urlresolvers/#django.urls.reverse), "viewname can be a URL pattern name or the callable view object". Please include the specific error you get if this is not working. – shriakhilc May 13 '22 at 14:09
  • reverse(url_name) works at the moment, i may have mistyped the name while post the question. Thanks for commenting – UselessFire May 13 '22 at 17:05

1 Answers1

8

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.

Chillie
  • 1,356
  • 13
  • 16
  • Yep, i read that in the documentation before your answer, but thanks anyway. This question can't be googled by direct request, so i hope it can help someone – UselessFire May 13 '22 at 17:03