Skip to content

Commit

Permalink
Refactor FullUrlMixin get_domain to handle django.contrib.sites not i…
Browse files Browse the repository at this point in the history
…n INSTALLED_APPS (#194)
  • Loading branch information
protoroto committed Dec 13, 2023
1 parent 1a4de31 commit d2a658d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
1 change: 1 addition & 0 deletions changes/192.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Refactor FullUrlMixin get_domain to handle django.contrib.sites not in INSTALLED_APPS
14 changes: 9 additions & 5 deletions meta/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
19 changes: 18 additions & 1 deletion tests/test_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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")

0 comments on commit d2a658d

Please sign in to comment.