From 1671d3025436baf6c8b874e2aec96dd5a85a8733 Mon Sep 17 00:00:00 2001 From: Leonardo Cavallucci Date: Wed, 13 Dec 2023 13:08:15 +0100 Subject: [PATCH] Refactor FullUrlMixin get_domain to handle django.contrib.sites not in INSTALLED_APPS --- changes/192.bugfix | 1 + meta/views.py | 14 +++++++++----- tests/test_meta.py | 19 ++++++++++++++++++- 3 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 changes/192.bugfix diff --git a/changes/192.bugfix b/changes/192.bugfix new file mode 100644 index 0000000..2fdd196 --- /dev/null +++ b/changes/192.bugfix @@ -0,0 +1 @@ +Refactor FullUrlMixin get_domain to handle django.contrib.sites not in INSTALLED_APPS diff --git a/meta/views.py b/meta/views.py index d06b82b..b2572d6 100644 --- a/meta/views.py +++ b/meta/views.py @@ -2,6 +2,7 @@ import warnings from datetime import date +from django.apps import apps from django.core.exceptions import ImproperlyConfigured from .settings import get_setting @@ -30,17 +31,20 @@ def get_domain(self): :return: domain URL """ - from django.contrib.sites.models import Site - try: - if self.use_sites: - return Site.objects.get_current(self.request).domain + use_site = self.use_sites except AttributeError: - if get_setting("USE_SITES"): + use_site = get_setting("USE_SITES") + + if use_site: + try: + Site = apps.get_model("sites.Site") try: return Site.objects.get_current(self.request).domain except AttributeError: return Site.objects.get_current().domain + except LookupError: + raise ImproperlyConfigured("Add django.contrib.sites to INSTALLED_APPS because META_USE_SITES is True") if not get_setting("SITE_DOMAIN"): raise ImproperlyConfigured("META_SITE_DOMAIN is not set") return get_setting("SITE_DOMAIN") diff --git a/tests/test_meta.py b/tests/test_meta.py index b23ca15..0dd3220 100644 --- a/tests/test_meta.py +++ b/tests/test_meta.py @@ -3,7 +3,7 @@ from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured -from django.test import RequestFactory, TestCase, override_settings +from django.test import RequestFactory, TestCase, modify_settings, override_settings from meta.views import Meta @@ -266,3 +266,20 @@ def test_as_json_ld(self): m.as_json_ld(), json.dumps(data), ) + + @override_settings(META_SITE_DOMAIN="example-no-sites.com", META_SITE_PROTOCOL="http") + @modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}) + def test_get_full_url_without_sites(self): + m = Meta() + self.assertEqual(m.get_full_url("foo/bar"), "http://example-no-sites.com/foo/bar") + + @override_settings( + META_SITE_DOMAIN="example-no-sites.com", + META_SITE_PROTOCOL="http", + META_USE_SITES=True, + ) + @modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}) + def test_get_full_url_without_sites_wrong_setting(self): + m = Meta() + with self.assertRaises(ImproperlyConfigured): + self.assertEqual(m.get_full_url("foo/bar"), "http://example-no-sites.com/foo/bar")