When to use the Django get_absolute_url () method?

Django's documentation says:

get_absolute_url() to tell Django how to calculate the canonical URL for the object.

What does the canonical URL mean in this context?

I know from an SEO perspective that a canonical URL means choosing the best URL from similar URLs ( example.com, example.com/index.html). But this value does not fit into this context.

I know that this method provides some additional features in Django administration, redirection, etc. And I fully know how to use this method.

But what philosophy is behind this? I have never used it in my projects. Does this serve any special purpose?

+11
source share
4 answers

, -, . , , HTML , URL . .

, URL-. get_absolute_url() .

:

<!-- Bad -->
<a href="/language/category/product/{{product.pk}}">Link</a>

<!-- Good -->
<a href="{{product.get_absolute_url}}">Link</a>

URL

- URL. URL - "" URL- . URL-, :

/en/shoes/1-nike-shoes/
/en/shoes/1-nike-shoes?sort=price&order=asc
/en/shoes/1-nike-shoes?sort=price&order=desc

, 3 URL. " URL" , . . /en/shoes/1-nike-shoes/.

, URL- . , .

, Django. "" " URL-, ".

+16

. , django , .

get_absolute_url . Django, , .

+2

get_absolute_url DRY. URL-, . .

models.permalink, URL- .

@permalink get_absolute_url Django?

, URL-, , URL-.

0

:

URL , - http://...../products/abcdefg/ ( '/products/' slug).

models.py 'get_absolute_url', URL

models.py

class Products(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(blank=True, unique=True)
    description = models.TextField()

    def get_absolute_url(self):
        return f"/products/{self.slug}/"

productlist.html - get_absolute_url

{% for obj in object_list  %}
   <a href="{{obj.get_absolute_url}} ">{{obj.title}}</a> <br>
{% endfor %}

urls.py - URL

 path('/products/<slug>/', ProductDetails.as_view()),
0

Source: https://habr.com/ru/post/1673867/


All Articles