What is @permalink and get_absolute_url in Django?

By: Varghese Chacko 2 years, 4 months ago

What is @permalink and get_absolute_url in Django? When and why to use it?

Both @permalink and get_absolute_url are concerned with allowing you to reverse the URL for a particular object and should be used together. They are used anytime you need to provide a link to a particular object or want to display that object's specific URL (if it has one) to the user.

You could simply write your get_absolute_url method to return a hard coded string, but this wouldn't adhere to Django's philosophy of DRY (don't repeat yourself). Instead, there is the @permalink to make things more flexible.

class BlogPost(models.Model):
    name = modelsCharField()
    slug = models.SlugField(...)

    def get_absolute_url(self):
        return ("blog-detail", [self.slug,])

and in urls.py you may add

url(r'/blog/(?P<slug>[-w]+)/$', blog.views.blog_detail, name="blog-detail")

Django documentation discouraged use of the permalink decorator and encouraged use of reverse() in the body of the get_absolute_url method by 2013. The permalink decorator seemed to have vanished without a trace from the Django documentation by 2015, and it was finally removed in Django version 2.1

So, for a standard DRY way to create a permanent link to a single object view, use get_absolute_url() in your model like this:

class MyModel(models.Model):
    slug = models.SlugField()

    def get_absolute_url(self):
        return reverse('mymodel_detail', args=(self.slug,))

and then have an entry in urls.py that points to your view:

url(r'^(?P<slug>[-\w\d\_]+)/$', MyModelDetailView.as_view(), name='mymodel_detail'),

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.