get_absolute_url() vs {% url 'item:detail' %}

Why should I use get_absolute_url() instead of using {% url ‘item:detail’ %} in my Template?
It is revered as the right method but I don’t get why. I use the url tag for generating the URL. What is the advantage of get_absolute_url?

In my opinion, the biggest benefit of using it is that it allows your templates to be more generic. When you define a get_absolute_url for a model, then you can have multiple models using the same template. (For example, you might have a generic listing page that needs to refer to a model-specific detail page.)

Another benefit is that it removes a dependency between your application structure and the template, reducing the possibility that a refactoring of your urls will break a template.

1 Like

That never occurred to me.

Isn’t {% url ‘item:detail’ %} doing the same reverse() lookup like you could define in get_absolute_url()? Obviousy if you would hardcode the url in the template that would be the worst option.

Agreed - but I think it’s a case of “number of places” in which you need to look for a change. If you’re doing the reverse lookup only in get_absolute_url(), that’s only one location to check. If you’ve got them scattered around templates, then you need to check / verify every template where it’s being used.

1 Like