Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Invalidate the appropriate SITE_CACHE entry when saving a Site model.

This avoids the problem of, for example, saving a change to the Site model in
the admin interface and then seeing the wrong instanec returned in the next
call to get_current_site().

It's still possible to end up with an inconsistent cache if update() is used to
change the Site model, but that's pretty unavoidable. It's also a slightly odd
way to update a Site model, so if you really need to do that, you can manage to
call SiteManager.clear() at the same time.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@9908 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 0dd4ec654f4b22854df841d9ea8f463fdbdf99c3 1 parent 1306079
Malcolm Tredinnick authored February 27, 2009
10  django/contrib/sites/models.py
@@ -41,12 +41,18 @@ class Meta:
41 41
 
42 42
     def __unicode__(self):
43 43
         return self.domain
44  
-    
  44
+
  45
+    def save(self, *args, **kwargs):
  46
+        super(Site, self).save(*args, **kwargs)
  47
+        # Cached information will likely be incorrect now.
  48
+        if self.id in SITE_CACHE:
  49
+            del SITE_CACHE[self.id]
  50
+
45 51
     def delete(self):
46 52
         pk = self.pk
47 53
         super(Site, self).delete()
48 54
         try:
49  
-            del(SITE_CACHE[pk])
  55
+            del SITE_CACHE[pk]
50 56
         except KeyError:
51 57
             pass
52 58
 
15  django/contrib/sites/tests.py
@@ -3,7 +3,7 @@
3 3
 >>> from django.conf import settings
4 4
 >>> Site(id=settings.SITE_ID, domain="example.com", name="example.com").save()
5 5
 
6  
->>> # Make sure that get_current() does not return a deleted Site object.
  6
+# Make sure that get_current() does not return a deleted Site object.
7 7
 >>> s = Site.objects.get_current()
8 8
 >>> isinstance(s, Site)
9 9
 True
@@ -13,4 +13,17 @@
13 13
 Traceback (most recent call last):
14 14
 ...
15 15
 DoesNotExist: Site matching query does not exist.
  16
+
  17
+# After updating a Site object (e.g. via the admin), we shouldn't return a
  18
+# bogus value from the SITE_CACHE.
  19
+>>> _ = Site.objects.create(id=settings.SITE_ID, domain="example.com", name="example.com")
  20
+>>> site = Site.objects.get_current()
  21
+>>> site.name
  22
+u"example.com"
  23
+>>> s2 = Site.objects.get(id=settings.SITE_ID)
  24
+>>> s2.name = "Example site"
  25
+>>> s2.save()
  26
+>>> site = Site.objects.get_current()
  27
+>>> site.name
  28
+u"Example site"
16 29
 """

0 notes on commit 0dd4ec6

Please sign in to comment.
Something went wrong with that request. Please try again.