Creating a model mixin with URL-related methods

For every model that has its own page, it is good practice to define the get_absolute_url() method. This method can be used in templates and also in the Django admin site to preview the saved object. However, get_absolute_url() is ambiguous as it returns the URL path instead of the full URL. In this recipe, we will see how to create a model mixin that allows you to define either the URL path or the full URL by default, generate the other out of the box, and take care of the get_absolute_url() method that is being set.

Getting ready

If you haven't done it yet, create the utils package to save your mixins. Then, create the models.py file in the utils package (alternatively, if you create a reusable app, ...

Get Web Development with Django Cookbook - Second Edition 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.