Dynamically generate URLs for objects by defining the get_absolute_url()
method in your model class.
from django.db import models
from django.urls import reverse
class Article(models.Model):
title = models.CharField(max_length=120)
body = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article_detail', args=[(self.id)])
Then in your template, you can use this syntax to generate the correct URL for the object
<a href="{{ article.get_absolute_url }}">{{ article.title }}</a>
Another really good use of this method comes when you're in the admin; .
One place Django uses get_absolute_url() is in the admin app. If an object defines this method, the object-editing page will have a “View on site” link that will jump you directly to the object’s public view, as given by get_absolute_url(). Django docs
Happy coding!
Stuart Elimu