How to do it...

Execute the following steps, one by one:

  1. Add the following content to the models.py file of your utils package:
# utils/models.py
from urllib.parse import urlparse, urlunparse

from django.conf import settings
from django.db import models


class UrlMixin(models.Model):
"""
A replacement for get_absolute_url()
Models extending this mixin should have
either get_url or get_url_path implemented.
"""
class Meta:
abstract = True

def get_url(self):
if hasattr(self.get_url_path, "dont_recurse"):
raise NotImplementedError
try:
path = self.get_url_path()
except NotImplementedError:
raise
website_host = getattr(settings,
"SITE_HOST",

 "localhost:8000")
return f"http://{website_host}/{path}"
get_url.dont_recurse = True

def get_url_path(self):
if hasattr(self.get_url, "dont_recurse"):
raise NotImplementedError
try:
url = self.get_url()
except NotImplementedError:
raise
bits = urlparse(url)
return urlunparse(("", "") + bits[2:])
get_url_path.dont_recurse = True

def get_absolute_url(self):
return self.get_url_path()
  1. To use the mixin in your app, import the mixin from the utils package, inherit the mixin in your model class, and define the get_url_path() method, as follows:
# demo_app/models.py
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _

from utils.models import UrlMixin


class Idea(UrlMixin):
# ...

def get_url_path(self):
return reverse("idea-detail", kwargs={
"pk": str(self.pk),
})
  1. If you check this code in the staging or production environment, or run a local server with a different IP or port than the defaults, set the SITE_HOST in the local settings. You might do so by using environment variables, as discussed in the Creating and including local settings recipe in Chapter 1, Getting Started with Django 2.1. Alternatively, you can use a multi-file approach, like the one detailed in the Configuring settings for development, testing, staging, and production environments recipe, also in Chapter 1, Getting Started with Django 2.1. The latter would be set up as follows:
# settings.py or config/prod.py
# ...
SITE_HOST = 'www.example.com'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181