How To Use Django url Tag And reverse() Function To Avoid Url Hard Coded

Hard coded url in your Django template html files or views.py file is a bad practice. Because it is difficult to maintain url changes. If you change one url, you may need to change that url in a lot of pages. So Django provide template url tag and reverse function for you to avoid hard coded url in both template html files and view functions.

1. Define Url Pattern In Django Project urls.py File.

add dept emp views test case python file

Before we can use url tag or reverse function, we need to define url patterns in your Django project urls.py file like below. Please note the url pattern definition, the name parameter value should not be changed, because this value will be used in url tag and reverse function.

So you can change the url path regular expression ( the first parameter  ) or process view function name (the second parameter ) when you need, and the changes here will not make template html pages and view function source code be changed.

from django.conf.urls import url


url(r'^emp_detail/(?P<user_name>\w+)/(?P<mobile_number>\d{10,18})/$', views.emp_detail, name='emp_detail_name'),

2. Use Django url Tag In Template Html Files.

Now you can use Django url tag to render url link in template html file like below. You should provide the django-project-name:url-pattern-name (dept_emp:emp_detail_name) as url tag’s first parameter. And because this url will pass parameters to Django server, so you should add parameter name value pairs ( which has been defined in url path pattern in urls.py file ) in the url tag also.

{% for emp in emp_list %}
    <tr>
      ......
      <td><a href="{% url 'dept_emp:emp_detail_name' user_name=emp.user.username mobile_number=emp.emp_mobile %}">{{ emp.user.username }}</a></td>
      ......
    </tr>
{% endfor %}

3.Use reverse() Function In View Function.

If you want to get the url link by url path pattern name in views.py functions, you can use django.ulrs.reverse function. The reverse function’s first parameter should be django-project-name:url-pattern-name (dept_emp:emp_detail_name). The second parameter can be a list of url parameters value or a dictionary object which has param-name as key and param-value as value.

from django.urls import reverse

return reverse('dept_emp:emp_detail_name', args=[self.user.username, self.emp_mobile])

or

return reverse('dept_emp:emp_detail_name', kwargs={'user_name':self.user.username, 'mobile_number':self.emp_mobile})

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.