Canonical URLs for models

You can use the post_detail URL that you have defined in the preceding section to build the canonical URL for Post objects. The convention in Django is to add a get_absolute_url() method to the model that returns the canonical URL of the object. For this method, we will use the reverse() method that allows you to build URLs by their name and passing optional parameters. Edit your models.py file and add the following:

from django.urls import reverse

class Post(models.Model):
# ...
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])

We will use the get_absolute_url() method in our templates to link to specific posts.