Django 2 Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The UrlMixin class is an abstract model that has three methods, as follows:

  • get_url() retrieves the full URL of the object.
  • get_url_path() retrieves the absolute path of the object.
  • get_absolute_url() mimics the get_url_path() method.

The get_url() and get_url_path() methods are expected to be overwritten in the extended model class; for example, Idea. You can define get_url(), and get_url_path() will strip it to the path. Alternately, you can define get_url_path(), and get_url() will prepend the website URL to the beginning of the path.

The rule of thumb is to always overwrite the  get_url_path()  method.

In the templates, use get_url_path() when you need a link to an object on the same website, as follows:

<a href="{{ idea.get_url_path }}">{{ idea.title }}</a>

Use get_url() for links to be surfaced outside of the websites, such as in emails, RSS feeds, or APIs; an example is as follows:

<a href="{{ 
idea.get_url }}">{{ idea.title }}</a>

The default get_absolute_url() method will be used in the Django model administration for the View on site functionality, and might also be used by some third-party Django apps.