Django Url Tag And Reverse Function Example

Using url tag and reverse() function, you can avoid hard-coding urls in template html files and views. So that even if the url path changes, it has no effect on templates and views source code. In fact, in the template view, if you want to get the currently accessed url, it’s more convenient to use request.path or request.get_full_path(). Of course, if you want to use request object in templates, you should include ‘django.core.context_processors.request’ in the settings configuration item TEMPLATE_CONTEXT_PROCESSORS.

In the beginning, when develop applications with django, the url address was hard-coded in urls.py, views.py and template html files. This raises a problem that if you change the url address path of a page in urls.py, then everywhere use that page url path (views.py and template html files ) needs to be changed. If it’s a big project, there’s a lot of work to be done.

1. How To Use Django url Tag In Template Html Files.

But Django itself provides a method to avoid above issue, that is to use template url tag, the url tag is contained in django.conf.urls module. With url tag, no matter how the url address path in url patterns changes ( defined in urls.py ), the address source code in template html files do not need to be changed. 

1.1 Not Use url Tag In Template Html File.

For example, when the url tag is not used in template html file, you can define url patterns for the home page url address like below.

urlpatterns = patterns('',    
    (r'^home$','get_home_index' ),
)

Below is the html content in template files.

<a href="/home">Home Page</a>

And generally every page in the website should has a link to the home page, so there are so many home page link ( /home), but one day if you want to change the home page link to other like /index in urls.py file.

urlpatterns = patterns('',    
    (r'^index$','get_home_index' ),
)

You will find it is too difficult, you need to change almost all pages <a href=”/home”>Home Page</a> to  <a href=”/index”>Home Page</a>

1.2 Use url Tag In Template Html File.

With url tag, things are a lot different. If url tag is used in the template, you should add name parameter to the url in url patterns definition file urls.py like below.

urlpatterns = patterns('',    
    url(r'^home$','get_home_index' ,name="home_index"),
)

You should also change the html source code in template html file like below.

<a href="{%url 'app_name:home_index'%}">Home Page</a>

The app_name is the name of the app where the url resides in, and home_index is the name parameter’s value in url pattern definition url(r’^home$’,’get_home_index’, name= “home_index”). In this way, no matter how do you modify the address path of urlpatterns, the generated template url link will change with them automatically, but the template url tag source code do not need to change, which will save a lot of time.

Please note the url pattern’s url definition’s name parameter’s value is unique globally. This is because of web page url link should be unique globally in one website.

1.3 How To Include Parameters In Url Tag.

When urlpatterns address path contain parameters such as below.

(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$','get_news_list' ),

There are two parameters, the final page url address like http://www.code-learner.com/2019/03.

If you want to use url tag in template html files, you should do following changes.

  1. Add a name to this url pattern.
    url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$','get_news_list',name="news_archive" ),
  2. Add parameter value after url tag in html template file.
    <a href="{% url 'app_name:news_archive' 2019  03 %}">2019/03</a>
  3. You can also specify parameter value with parameter name like below.
    <a href="{%url 'app_name:news_archive' year=2019  month=03%}">2019/02</a>
    
    
  4. Do not forget add above two parameters in view function news_list in views.py file. The parameters are separated by comma.
    def news_list(request,year,month):
        print 'year:',year
        print 'monty:',month
        ......

2. How To Use reverse Function In Views.

Using url tag in templates is very simple, but what about using urls in views? In the past, when reverse function were not used, HttpResponseRedirect (“/home”) is used to point to an address. But when urlpatterns change address path, all views HttpResponseRedirect function’s arguments value will have to change accordingly.

With django.ulrs.reverse function, you can create the HttpResponseRedirect object like this HttpResponseRedirect (reverse (“home_index”)), the benefit of this is same as use url tag in template html files.

2.1 How To Include Parameters In reverse Function.

To generate url with parameters use reverse function, you can do in below two ways.

  1. Pass parameter name and value in a dictionary object, the dictionary object’s key is parameter name, the dictionary object’s value is parameter value.
    from django.urls import reverse
    ......
    reverse("app_name:news_archive",kwargs={"year":2019,"month":03})
  2. Pass parameter values in a list, the list item order is same as url pattern’s parameter order.
    from django.urls import reverse
    ......
    reverse("app_name:news_archive",args=[2019,03])

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.