Code

Ticket #19698: 19698-rebase-and-cleaned.diff

File 19698-rebase-and-cleaned.diff, 2.2 KB (added by serdaroncode, 14 months ago)
Line 
1diff --git a/django/contrib/sites/models.py b/django/contrib/sites/models.py
2index 8590740..5e6a330 100644
3--- a/django/contrib/sites/models.py
4+++ b/django/contrib/sites/models.py
5@@ -1,4 +1,5 @@
6 from django.db import models
7+from django.db.models.signals import pre_save, pre_delete
8 from django.utils.translation import ugettext_lazy as _
9 from django.utils.encoding import python_2_unicode_compatible
10 
11@@ -49,20 +50,6 @@ class Site(models.Model):
12     def __str__(self):
13         return self.domain
14 
15-    def save(self, *args, **kwargs):
16-        super(Site, self).save(*args, **kwargs)
17-        # Cached information will likely be incorrect now.
18-        if self.id in SITE_CACHE:
19-            del SITE_CACHE[self.id]
20-
21-    def delete(self):
22-        pk = self.pk
23-        super(Site, self).delete()
24-        try:
25-            del SITE_CACHE[pk]
26-        except KeyError:
27-            pass
28-
29 
30 @python_2_unicode_compatible
31 class RequestSite(object):
32@@ -96,3 +83,16 @@ def get_current_site(request):
33     else:
34         current_site = RequestSite(request)
35     return current_site
36+
37+
38+def clear_cache(sender, **kwargs):
39+    """
40+    Clears the cache (if primed) each time a site is saved or deleted
41+    """
42+    instance = kwargs['instance']
43+    try:
44+        del SITE_CACHE[instance.pk]
45+    except KeyError:
46+        pass
47+pre_save.connect(clear_cache)
48+pre_delete.connect(clear_cache)
49diff --git a/django/contrib/sites/tests.py b/django/contrib/sites/tests.py
50index cdbd78b..ee6224b 100644
51--- a/django/contrib/sites/tests.py
52+++ b/django/contrib/sites/tests.py
53@@ -42,6 +42,13 @@ class SitesFrameworkTests(TestCase):
54         site = Site.objects.get_current()
55         self.assertEqual("Example site", site.name)
56 
57+    def test_delete_all_sites_clears_cache(self):
58+        # When all site objects are deleted the cache should also
59+        # be cleared and get_current() should raise a DoesNotExist.
60+        self.assertIsInstance(Site.objects.get_current(), Site)
61+        Site.objects.all().delete()
62+        self.assertRaises(Site.DoesNotExist, Site.objects.get_current)
63+
64     @override_settings(ALLOWED_HOSTS=['example.com'])
65     def test_get_current_site(self):
66         # Test that the correct Site object is returned