Tidbits | Aug. 11, 2016

Pro-Tip – reverse()'s soulmate resolve()

by Flavio Curella

One common practice in Django is reversing URL:

from django.urls import reverse

reverse('my_url_name', kwargs={'pk': 1})

But very often, in large projects, it's hard to remember exactly what the name of the URL is. Furthermore, you maybe using 3rd party libraries that include URLs you want to refer to.

If you know what the URL looks like, but you can't remember the name or its arguments, a quick and easy way to find them out is use the `resolve` function:

from django.urls import resolve

# ResolverMatch(func=myapp.views.MyModelViewSet, args=(), kwargs={u'pk': u'2'}, url_name=mymodel-detail, app_name=None, namespaces=['api'])

As you can see, the output includes all you need to reverse the URL, including arguments, app_name and namespaces.


The django-extensions package provides another easy way to find out which view. After installing it, you can simply use its show_urls and grepping for the URL you're looking for:

$ ./manage.py show_urls | grep "/myurl/<pk>"

Thanks to @bmihelac for the suggestion!

Have a URL but can't figure out what view it is supposed to use? Use resolve() to easily and quickly determine it just as Django does.

2016-08-11T07:29:46.458050 2017-06-01T12:17:09.810358 2016 python,django