How to Create Django Template Absolute URL (Dynamic URL Generation)
A key concept in Django is to reduce code repetition and hardcoding of data, which is especially important in the case of template links. If a URL needs to be changed in the app in the future we don't want to go through a bunch of files to implement it, which is why it is good practice to use absolute URL's.
To use absolute URLs in your app template files, create a function called get_absolute_url()
in your models.py
file like this:
def get_absolute_url(self):
return reverse('my_app:my_app', kwargs={'slug': self.slug })
Then at the top of the models.py
file import the reverse()
function like this:
from django.urls import reverse
The Django reverse()
function will look for a matching pattern in your urls.py
file and use it to generate a dynamic URL based on the data supplied. If you have dynamic URL segments, supply them as a dictionary with kwargs
.
Next, make sure you have defined the app name in the urls.py
file like this:
app_name = 'my_app'
urlpatterns = [
path(...
Now in a template, pass an object to the absolute URL generator like this:
{% for i in object_list %}
<a href="{{ i.get_absolute_url }}">{{ i.name }}</a>
{% endfor %}