6.2.3 Canonical Model URLs

Each of our model objects is displayed only on a single webpage, which means that each model object effectively has a single, canonical URL to access its full information. Our website will display the Tag titled Django if and only if a user requests the URL path /tag/django/.

Instead of calling reverse() with tag.slug, it is easier to ask the model for its URL directly. It results in shorter code, better adheres to DRY, and is what Django recommends.

In fact, Django not only recommends having a method on each model to create a canonical URL but expects us to name this method get_absolute_url(). Once we have it programmed, it allows us to code as shown in Example 6.9.

Example 6.9: Python Interpreter Code

Get Django Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.