|
@@ -34,26 +34,39 @@ def _simple_domain_name_validator(value):
|
|
|
|
|
|
class SiteManager(models.Manager):
|
|
|
|
|
|
- def get_current(self):
|
|
|
+ def _get_site_by_id(self, site_id):
|
|
|
+ if site_id not in SITE_CACHE:
|
|
|
+ site = self.get(pk=site_id)
|
|
|
+ SITE_CACHE[site_id] = site
|
|
|
+ return SITE_CACHE[site_id]
|
|
|
+
|
|
|
+ def _get_site_by_request(self, request):
|
|
|
+ host = request.get_host()
|
|
|
+ if host not in SITE_CACHE:
|
|
|
+ site = self.get(domain__iexact=host)
|
|
|
+ SITE_CACHE[host] = site
|
|
|
+ return SITE_CACHE[host]
|
|
|
+
|
|
|
+ def get_current(self, request=None):
|
|
|
"""
|
|
|
- Returns the current ``Site`` based on the SITE_ID in the
|
|
|
- project's settings. The ``Site`` object is cached the first
|
|
|
- time it's retrieved from the database.
|
|
|
+ Returns the current Site based on the SITE_ID in the project's settings.
|
|
|
+ If SITE_ID isn't defined, it returns the site with domain matching
|
|
|
+ request.get_host(). The ``Site`` object is cached the first time it's
|
|
|
+ retrieved from the database.
|
|
|
"""
|
|
|
from django.conf import settings
|
|
|
- try:
|
|
|
- sid = settings.SITE_ID
|
|
|
- except AttributeError:
|
|
|
- raise ImproperlyConfigured(
|
|
|
- "You're using the Django \"sites framework\" without having "
|
|
|
- "set the SITE_ID setting. Create a site in your database and "
|
|
|
- "set the SITE_ID setting to fix this error.")
|
|
|
- try:
|
|
|
- current_site = SITE_CACHE[sid]
|
|
|
- except KeyError:
|
|
|
- current_site = self.get(pk=sid)
|
|
|
- SITE_CACHE[sid] = current_site
|
|
|
- return current_site
|
|
|
+ if getattr(settings, 'SITE_ID', ''):
|
|
|
+ site_id = settings.SITE_ID
|
|
|
+ return self._get_site_by_id(site_id)
|
|
|
+ elif request:
|
|
|
+ return self._get_site_by_request(request)
|
|
|
+
|
|
|
+ raise ImproperlyConfigured(
|
|
|
+ "You're using the Django \"sites framework\" without having "
|
|
|
+ "set the SITE_ID setting. Create a site in your database and "
|
|
|
+ "set the SITE_ID setting or pass a request to "
|
|
|
+ "Site.objects.get_current() to fix this error."
|
|
|
+ )
|
|
|
|
|
|
def clear_cache(self):
|
|
|
"""Clears the ``Site`` object cache."""
|
|
@@ -103,5 +116,9 @@ def clear_site_cache(sender, **kwargs):
|
|
|
del SITE_CACHE[instance.pk]
|
|
|
except KeyError:
|
|
|
pass
|
|
|
+ try:
|
|
|
+ del SITE_CACHE[Site.objects.get(pk=instance.pk).domain]
|
|
|
+ except (KeyError, Site.DoesNotExist):
|
|
|
+ pass
|
|
|
pre_save.connect(clear_site_cache, sender=Site)
|
|
|
pre_delete.connect(clear_site_cache, sender=Site)
|