[Django]-Django url_for equivalent

6👍

It depends what you’re looking for.

Static Files

If you want to get the URL for a static file, you can use the following bit:

from django.templatetags.static import static

url = static('images/myPic.jpg')

URL config

If you want to get the URL path of a named URL in your URL config, you can use the the reverse URL resolver. Let’s say your URL config looks like this:

If your URL config would look like this:

from example import views

path('my/fancy/example/', views.example, name='my-example-view')

Then you can get the URL with this:

from django.urls import reverse

url = reverse('my-example-view') # will return "my/fancy/example/"

1👍

I use the template tag in my python files as well when I need that:

from django.contrib.staticfiles.templatetags.staticfiles import static

url = static('images/myPic.jpg')

Leave a comment