Adding reverse url lookup in Django

Reverse url lookup is very cool feature in Django that allows us to not hard-code urls in templates or controller logic. This helps us change the URLs later in urls.py and not have to make the same changes everywhere in templates and logic. Keep it DRY.

To implement reverse url lookup, you need to do these:

  1. Make a namespace (if your urls are inside an app… otherwise omit this step). Making a namespace makes it possible to have multiple apps use the same name for named urls.
  2. make the named url

The main url (same level as settings.py). Note that the namespace is set here:

Then the urls.py in the app econ_product:

Now you can use the url lookup.

Note, the lookup is done differently in template and in controller logic. In controller logic, we will need a reverse() call to construct the url for us. Like so:
(Here I am doing a reverse url lookup in models.py in the method get_absolute_url like so: reverse('ecom_product:detail', kwargs={'slug':self.slug}))

Here: ecom_product is the namespace and detail is the url name in that namespace.
Note also that kwargs passed corresponds to the parameter slug in the url
url(r'^(?P<slug>[\w-]+)/$', EcomProductDetailSlugView.as_view(), name='detail'),

In a template, we do the url lookup like so {% url 'ecom_product:detail' slug=instance.slug %}:




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *