def anonymous_or_real(request): # do we have an existing user? if request.user.is_authenticated(): return request.user else: # if not, create an anonymous user and log them in username = IntToLetters(randint(0, maxint)) u = User(username=username, first_name='Anonymous', last_name='User') u.set_unusable_password() u.save() u.username = u.id u.save() # comment out the next two lines if you aren't using profiles p = UserProfile(user=u, anonymous=True) p.save() authenticate(user=u) login(request, u) return u ######## Anonymous authentication backend middleware ######### from django.contrib.auth.models import User from myapp.models import UserProfile class AuthenticationBackendAnonymous: ''' This is for automatically signing in the user after signup etc. ''' def authenticate(self, user=None): # make sure they have a profile and that they are anonymous # if you're not using profiles you can just return user if not user.get_profile() or not user.get_profile().anonymous: user = None return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None