How to Highlight Active Links in your Django Website
If you happen to create websites or full web applications using frameworks or from scratch, then you have probably find yourself looking for how to mark active links as active. In Django, it is pretty simple. Here is how I do it.
The normal way

Let's say you have a navbar like the one above and you want to highlight the current active link so that the user knows on which page he is now. You can easily implement that navbar with the following code (using Bootstrap):
What we want to do is to automatically add the CSS active
For that we need to have the request object in the current page. Go ahead and ensure that django.template.context_processors.request
TEMPLATES = [
{
# ... (truncated other options for readability)
"OPTIONS": {
# ...
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request", # Make sure you have this line
"django.contrib.auth.context_processors.auth",
# ...
],
},
}
]
Then you can use the request
Now if you navigate to the about page, you will see something like this:

Notice how the Home and About link are activated (displayed with a different color). Also notice how About link still looks activated? That's because we didn't remove the active
Now if we navigate to each of the links of the navbar, we will see the corresponding link displayed with a different color from the others.
Only thing I don't like about this method, you have to store the link in a variable before being able to use it in the if
The easiest way
Django Active Link is pretty simple to use. First go ahead and add it to your project with:
Then add it to your installed apps:
INSTALLED_APPS = (
...
'active_link',
...
)
To start using the template tag in your templates you need to load it first:
Now to mark the Home menu active when the user is on the Home page, we just have to use the active_link
Where homeactive
Conclusion
That's it. You can now highlight the active links in your Django application with ease. You can even do it without an exact match. Like marking the URL /blog/blog/categoriesin
Or rely on Django Active Link to take care of all that for you. You can find more in the Documentation.
Thank you for reading. I hope you found it useful.
