Commits

Chris Chambers  committed f7f9bc8

Creator/EditorFields handle AnonymousUsers correctly

  • Participants
  • Parent commits bfc0422

Comments (0)

Files changed (2)

File tests/model_tests/tests.py

 from models import Article, ArticleCreator, ArticleEditor
-from django.contrib.auth.models import User
+from django.contrib.auth.models import User, AnonymousUser
 from threaded_multihost.threadlocals import get_current_user, set_current_user
 
 __test__ = {'API_TESTS': """
 >>> c.user
 <User: editor>
 
+# If the fields get an AnonymousUser from threadlocals, they should handle them
+# appropriately and save NULL values to the database:
+>>> anon = AnonymousUser()
+>>> set_current_user(anon)
+
+>>> anonb = ArticleCreator.objects.create(text="foo")
+>>> anonb.user is None
+True
+>>> anonb = ArticleCreator.objects.get(pk=anonb.pk)
+>>> anonb.user is None
+True
+
+>>> anonc = ArticleEditor.objects.create(text="bar")
+>>> anonc.user is None
+True
+>>> anonc = ArticleEditor.objects.get(pk=anonc.pk)
+>>> anonc.user is None
+True
 """}

File threaded_multihost/fields.py

     By default, sets editable=False, default=threadlocals.get_current_user
     """
 
+    def get_current_user(self):
+        user = threadlocals.get_current_user()
+        if user and not user.is_authenticated():
+            user = None
+        return user
+
     def __init__(self, **kwargs):
         kwargs.setdefault('editable', False)
-        kwargs.setdefault('default', threadlocals.get_current_user)
+        kwargs.setdefault('default', self.get_current_user)
         UserField.__init__(self, **kwargs)
 
 
         super(CreatorField, self).__init__(**kwargs)
 
     def pre_save(self, model_instance, add):
-        value = threadlocals.get_current_user()
+        value = self.get_current_user()
         setattr(model_instance, self.name, value)
         if value:
             value = value.pk