Relative URLs

Let's discuss how to use template tagging to create relative URLs.

What are relative URLs?

Traditionally, when we use an anchor tag with an href, we have to pass in the hardcoded path to the file. However, this method is not suitable if we want our Django project to work on any system. So let’s see how to replace a hardcoded URL path in an href with a URL template.

Using the url tag

The best way to replace a hardcoded URL path in a Django template is to use the url tag. The syntax for the url tag is as follows:

{% url 'some-url-name' arg1=v1 arg2=v2 %}

For example, if we had the following URL before:

<a href= "/profile/12" >Profile</a>

The path defined for this URL in the project’s urls.py is the following:

path('/profile/<int:id>', views.profile, name='show-profile')

Then, after modification it will become:

<a href = "{% url 'show-profile' id=12 %}">Profile</a>

As we can see from the example above, we use the name parameter defined in path to refer to the URL in the url tag. Additionally, the id parameter is passed in the url tag.

Let’s discuss another example, where we want to reference the path of a specific application. This can easily be done by adding the application name, followed by a colon, before the name parameter. Take a look at the following URL:

{% url 'my_app:index' %}

In this example, my_app is the name of our application and home is the name of the path that we have set in the application’s urls.py.

Let’s understand this more clearly by seeing all the steps involved in it:

Step 1: Set the variable app_name

In this step, we have to go inside the urls.py file and add in the variable app_name, and then set the variable equal to the string that is the same name as our application name. We will add the following line in our zing_it/urls.py application:

app_name = 'zing_it'

Step 2: Use the name of the path

In this step, we basically use the name of the path that we specified. For example, if we have a URL by the name of search in our zing_it application, we would write the following:

<a href= "{% url 'zing_it:search' %}">Search Page</a>

In this example, zing_it is the name of our application and search is the name of our search URL defined in the zing_it/urls.py file.

Get hands-on with 1200+ tech skills courses.