python / beginner
Snippet
Implementing the get_absolute_url Pattern
This method is a standard pattern that tells Django how to calculate the canonical URL for an object, making it easy to link to from templates.
snippet.py
1
2
3
4
5
6
from django.urls import reversefrom django.db import modelsclass Product(models.Model):def get_absolute_url(self):return reverse('product-detail', kwargs={'slug': self.slug})
django
Breakdown
1
from django.urls import reverse
Imports the utility to resolve URL names into actual paths.
2
return reverse(...)
Generates the URL path using the 'product-detail' name and the object's slug.