Skip to content

Instantly share code, notes, and snippets.

@stuartelimu
Last active July 5, 2020 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartelimu/76406d6ab7acaa67bd8083bc73a421a9 to your computer and use it in GitHub Desktop.
Save stuartelimu/76406d6ab7acaa67bd8083bc73a421a9 to your computer and use it in GitHub Desktop.
Using get_absolute_url() model instance method in Django

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

Web / Twitter / Github

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment