Using Reverse URL lookup in Django

20 February, 2016
Python Django

After coding and working with django, through several projects and refactoring. I found reverse url lookup feature of django to work on clean working

Problem
You want to avoid hard-coding URL links in view methods and templates to make it easier to update and add new URLs.


Solution Use the name and namespace attributes on your project's URL definitions. Use the reverse method in view methods or the {% url %} tag in templates to reference project URLs. In addition, you can also use the app_name attribute to further classify URLs for multiple app instances.

How it works
Links or URL references tend to be hard-coded in a project's codebase. Whether it's in view methods to redirect users to certain locations or in templates to provide adequate user navigation. Hard-coding such links can present a serious maintenance problem leading to difficult to detect dead links once a project grows. Django offers a way to name URLs so it's easy to reference them in view methods and templates.
The most basic technique to name Django urls is to add the name attribute to url method definitions in urls.py. Listing 1 shows how to name a project's home page, as well as how to reference this URL from a view method or template.


Let's see where and how to use django named and reverse lookup feature.
When you are setting up web application, you must have static or dynamic pages. And you like to provide the links to the page somewhere in your applications. There are three places where url's are getting configured. urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'project.views.home', name='home'),
    url(r'^blog/(?P[\w\d\-]+)-(?P[\d]+)$', 'blog.views.blog_post',
                           name='blog_post'),
    url(r'^admin/', include(admin.site.urls)),
)

Now here you see in first urls rule i have added a extra parameter saying it's name = "home" and similar for blog_post, which means the url configuration is a named url. In order to access it templates or views there are ways to for dynamic name urls and static based one. Let's see.

models.py


class Blog(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100)

    @permalink
    def get_absolute_url(self):
        return ('blog_post', None, {'slug': self.slug, 'identifier': self.id})

As you can see here. Permalink decorator has been used to specific feature of django to tell django to auto generate urls for the model object. Or you can use reverse method provided by django to do the same. Now in your templates to get a clean url
{{ blog.get_absolute_url }}



I have been writing a lot of posts. Looking forward to any feedbacks.
Thank you for taking the time to read this post. If you're considering using Digital Ocean, the hosting provider this blog is hosted on, please consider using this link to sign up.