Commits

Andrei Sosnin committed 4235960

Substitute all cases of using User with get_user_model()

  • Participants
  • Parent commits 9e1c772

Comments (0)

Files changed (7)

registration/backends/simple/views.py

 from django.conf import settings
 from django.contrib.auth import authenticate
 from django.contrib.auth import login
-from django.contrib.auth.models import User
 
 from registration import signals
+from registration.compat import get_user_model
 from registration.views import RegistrationView as BaseRegistrationView
 
 
     workflow: a user supplies a username, email address and password
     (the bare minimum for a useful account), and is immediately signed
     up and logged in).
-    
+
     """
     def register(self, request, **cleaned_data):
         username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
-        User.objects.create_user(username, email, password)
+        get_user_model().objects.create_user(username, email, password)
 
         new_user = authenticate(username=username, password=password)
         login(request, new_user)
 
         * If ``REGISTRATION_OPEN`` is both specified and set to
           ``False``, registration is not permitted.
-        
+
         """
         return getattr(settings, 'REGISTRATION_OPEN', True)
 

registration/forms.py

 from django import forms
 from django.utils.translation import ugettext_lazy as _
 
+from registration.compat import get_user_model
+
 
 class RegistrationForm(forms.Form):
     """
     Form for registering a new user account.
-    
+
     Validates that the requested username is not already in use, and
     requires the password to be entered twice to catch typos.
-    
+
     Subclasses should feel free to add any additional validation they
     need, but should avoid defining a ``save()`` method -- the actual
     saving of collected user data is delegated to the active
 
     """
     required_css_class = 'required'
-    
+
     username = forms.RegexField(regex=r'^[\w.@+-]+$',
                                 max_length=30,
                                 label=_("Username"),
-                                error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
+                                error_messages={'invalid': _("This value may contain only letters, "
+                                                             "numbers and @/./+/-/_ characters.")})
     email = forms.EmailField(label=_("E-mail"))
     password1 = forms.CharField(widget=forms.PasswordInput,
                                 label=_("Password"))
     password2 = forms.CharField(widget=forms.PasswordInput,
                                 label=_("Password (again)"))
-    
+
     def clean_username(self):
         """
         Validate that the username is alphanumeric and is not already
         in use.
-        
+
         """
-        existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
+        existing = get_user_model().objects.filter(username__iexact=self.cleaned_data['username'])
         if existing.exists():
             raise forms.ValidationError(_("A user with that username already exists."))
         else:
         match. Note that an error here will end up in
         ``non_field_errors()`` because it doesn't apply to a single
         field.
-        
+
         """
         if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
             if self.cleaned_data['password1'] != self.cleaned_data['password2']:
     """
     Subclass of ``RegistrationForm`` which adds a required checkbox
     for agreeing to a site's Terms of Service.
-    
+
     """
     tos = forms.BooleanField(widget=forms.CheckboxInput,
                              label=_(u'I have read and agree to the Terms of Service'),
     """
     Subclass of ``RegistrationForm`` which enforces uniqueness of
     email addresses.
-    
+
     """
     def clean_email(self):
         """
         Validate that the supplied email address is unique for the
         site.
-        
+
         """
-        if User.objects.filter(email__iexact=self.cleaned_data['email']):
-            raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
+        if get_user_model().objects.filter(email__iexact=self.cleaned_data['email']):
+            raise forms.ValidationError(_("This email address is already in use. Please supply a different "
+                                          "email address."))
         return self.cleaned_data['email']
 
 
     Subclass of ``RegistrationForm`` which disallows registration with
     email addresses from popular free webmail services; moderately
     useful for preventing automated spam registrations.
-    
+
     To change the list of banned domains, subclass this form and
     override the attribute ``bad_domains``.
-    
+
     """
     bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
                    'googlemail.com', 'hotmail.com', 'hushmail.com',
                    'msn.com', 'mail.ru', 'mailinator.com', 'live.com',
                    'yahoo.com']
-    
+
     def clean_email(self):
         """
         Check the supplied email address against a list of known free
         webmail domains.
-        
+
         """
         email_domain = self.cleaned_data['email'].split('@')[1]
         if email_domain in self.bad_domains:
-            raise forms.ValidationError(_("Registration using free email addresses is prohibited. Please supply a different email address."))
+            raise forms.ValidationError(_("Registration using free email addresses is prohibited. Please "
+                                          "supply a different email address."))
         return self.cleaned_data['email']

registration/models.py

 class RegistrationManager(models.Manager):
     """
     Custom manager for the ``RegistrationProfile`` model.
-    
+
     The methods defined here provide shortcuts for account creation
     and activation (including generation and emailing of activation
     keys), and for cleaning out expired inactive accounts.
-    
+
     """
     def activate_user(self, activation_key):
         """
         Validate an activation key and activate the corresponding
         ``User`` if valid.
-        
+
         If the key is valid and has not expired, return the ``User``
         after activating.
-        
+
         If the key is not valid or has expired, return ``False``.
-        
+
         If the key is valid but the ``User`` is already active,
         return ``False``.
-        
+
         To prevent reactivation of an account which has been
         deactivated by site administrators, the activation key is
         reset to the string constant ``RegistrationProfile.ACTIVATED``
                 profile.save()
                 return user
         return False
-    
+
     def create_inactive_user(self, username, email, password,
                              site, send_email=True):
         """
 
         By default, an activation email will be sent to the new
         user. To disable this, pass ``send_email=False``.
-        
+
         """
-        new_user = get_user_model().objects.create_user(username, email, password)
+        new_user = get_user_model().objects.create_user(
+            username=username, email=email, password=password)
         new_user.is_active = False
         new_user.save()
 
         """
         Create a ``RegistrationProfile`` for a given
         ``User``, and return the ``RegistrationProfile``.
-        
+
         The activation key for the ``RegistrationProfile`` will be a
         SHA1 hash, generated from a combination of the ``User``'s
         username and a random salt.
-        
+
         """
         salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
-        username = user.username
+        try:
+            # Django >= 1.5
+            username = user.get_username()
+        except AttributeError:
+            # Django < 1.5
+            username = user.username
         if isinstance(username, unicode):
             username = username.encode('utf-8')
         activation_key = hashlib.sha1(salt+username).hexdigest()
         return self.create(user=user,
                            activation_key=activation_key)
-        
+
     def delete_expired_users(self):
         """
         Remove expired instances of ``RegistrationProfile`` and their
         associated ``User``s.
-        
+
         Accounts to be deleted are identified by searching for
         instances of ``RegistrationProfile`` with expired activation
         keys, and then checking to see if their associated ``User``
         instances have the field ``is_active`` set to ``False``; any
         ``User`` who is both inactive and has an expired activation
         key will be deleted.
-        
+
         It is recommended that this method be executed regularly as
         part of your routine site maintenance; this application
         provides a custom management command which will call this
         method, accessible as ``manage.py cleanupregistration``.
-        
+
         Regularly clearing out accounts which have never been
         activated serves two useful purposes:
-        
+
         1. It alleviates the ocasional need to reset a
            ``RegistrationProfile`` and/or re-send an activation email
            when a user does not receive or does not act upon the
            initial activation email; since the account will be
            deleted, the user will be able to simply re-register and
            receive a new activation key.
-        
+
         2. It prevents the possibility of a malicious user registering
            one or more accounts and never activating them (thus
            denying the use of those usernames to anyone else); since
            those accounts will be deleted, the usernames will become
            available for use again.
-        
+
         If you have a troublesome ``User`` and wish to disable their
         account while keeping it in the database, simply delete the
         associated ``RegistrationProfile``; an inactive ``User`` which
         does not have an associated ``RegistrationProfile`` will not
         be deleted.
-        
+
         """
         for profile in self.all():
             try:
     """
     A simple profile which stores an activation key for use during
     user account registration.
-    
+
     Generally, you will not want to interact directly with instances
     of this model; the provided manager includes methods
     for creating and activating new accounts, as well as for cleaning
     out accounts which have never been activated.
-    
+
     While it is possible to use this model as the value of the
     ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
     so. This model's sole purpose is to store data temporarily during
     account registration and activation.
-    
+
     """
     ACTIVATED = u"ALREADY_ACTIVATED"
     
     user = models.ForeignKey(AUTH_USER_MODEL, unique=True, verbose_name=_('user'))
     activation_key = models.CharField(_('activation key'), max_length=40)
-    
+
     objects = RegistrationManager()
-    
+
     class Meta:
         verbose_name = _('registration profile')
         verbose_name_plural = _('registration profiles')
-    
+
     def __unicode__(self):
         return u"Registration information for %s" % self.user
-    
+
     def activation_key_expired(self):
         """
         Determine whether this ``RegistrationProfile``'s activation
         key has expired, returning a boolean -- ``True`` if the key
         has expired.
-        
+
         Key expiration is determined by a two-step process:
-        
+
         1. If the user has already activated, the key will have been
            reset to the string constant ``ACTIVATED``. Re-activating
            is not permitted, and so this method returns ``True`` in
            activate their account); if the result is less than or
            equal to the current date, the key has expired and this
            method returns ``True``.
-        
+
         """
         expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
         return self.activation_key == self.ACTIVATED or \
         """
         Send an activation email to the user associated with this
         ``RegistrationProfile``.
-        
+
         The activation email will make use of two templates:
 
         ``registration/activation_email_subject.txt``
                                    ctx_dict)
         # Email subject *must not* contain newlines
         subject = ''.join(subject.splitlines())
-        
+
         message = render_to_string('registration/activation_email.txt',
                                    ctx_dict)
-        
+
         self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
-    
+

registration/tests/default_backend.py

 
 from registration import signals
 from registration.admin import RegistrationAdmin
+from registration.compat import get_user_model
 from registration.forms import RegistrationForm
 from registration.backends.default.views import RegistrationView
 from registration.models import RegistrationProfile
         # the 'registration is closed' message.
         resp = self.client.get(reverse('registration_register'))
         self.assertRedirects(resp, reverse('registration_disallowed'))
-        
+
         resp = self.client.post(reverse('registration_register'),
                                 data={'username': 'bob',
                                       'email': 'bob@example.com',
         """
         HTTP ``GET`` to the registration view uses the appropriate
         template and populates a registration form into the context.
-        
+
         """
         resp = self.client.get(reverse('registration_register'))
         self.assertEqual(200, resp.status_code)
                                       'password2': 'secret'})
         self.assertRedirects(resp, reverse('registration_complete'))
 
-        new_user = User.objects.get(username='bob')
+        new_user = get_user_model().objects.get(username='bob')
 
         self.failUnless(new_user.check_password('secret'))
         self.assertEqual(new_user.email, 'bob@example.com')
 
         # New user must not be active.
         self.failIf(new_user.is_active)
-        
+
         # A registration profile was created, and an activation email
         # was sent.
         self.assertEqual(RegistrationProfile.objects.count(), 1)
         Registration still functions properly when
         ``django.contrib.sites`` is not installed; the fallback will
         be a ``RequestSite`` instance.
-        
+
         """
         Site._meta.installed = False
 
                                       'password2': 'secret'})
         self.assertEqual(302, resp.status_code)
 
-        new_user = User.objects.get(username='bob')
+        new_user = get_user_model().objects.get(username='bob')
 
         self.failUnless(new_user.check_password('secret'))
         self.assertEqual(new_user.email, 'bob@example.com')
 
         self.failIf(new_user.is_active)
-        
+
         self.assertEqual(RegistrationProfile.objects.count(), 1)
         self.assertEqual(len(mail.outbox), 1)
 
     def test_registration_failure(self):
         """
         Registering with invalid data fails.
-        
+
         """
         resp = self.client.post(reverse('registration_register'),
                                 data={'username': 'bob',
     def test_activation(self):
         """
         Activation of an account functions properly.
-        
+
         """
         resp = self.client.post(reverse('registration_register'),
                                 data={'username': 'bob',
     def test_activation_expired(self):
         """
         An expired account can't be activated.
-        
+
         """
         resp = self.client.post(reverse('registration_register'),
                                 data={'username': 'bob',

registration/tests/forms.py

-from django.contrib.auth.models import User
 from django.test import TestCase
 
+from registration.compat import get_user_model
 from registration import forms
 
 
         """
         # Create a user so we can verify that duplicate usernames aren't
         # permitted.
-        User.objects.create_user('alice', 'alice@example.com', 'secret')
+        get_user_model().objects.create_user('alice', 'alice@example.com', 'secret')
 
         invalid_data_dicts = [
             # Non-alphanumeric username.
         """
         # Create a user so we can verify that duplicate addresses
         # aren't permitted.
-        User.objects.create_user('alice', 'alice@example.com', 'secret')
+        get_user_model().objects.create_user('alice', 'alice@example.com', 'secret')
 
         form = forms.RegistrationFormUniqueEmail(data={'username': 'foo',
                                                        'email': 'alice@example.com',

registration/tests/models.py

 from django.test import TestCase
 from django.utils.hashcompat import sha_constructor
 
+from registration.compat import get_user_model
 from registration.models import RegistrationProfile
 
 
 class RegistrationModelTests(TestCase):
     """
     Test the model and manager used in the default backend.
-    
+
     """
     user_info = {'username': 'alice',
                  'password': 'swordfish',
                  'email': 'alice@example.com'}
-    
+
     def setUp(self):
         self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
         settings.ACCOUNT_ACTIVATION_DAYS = 7
         Creating a registration profile for a user populates the
         profile with the correct user and a SHA1 hash to use as
         activation key.
-        
+
         """
-        new_user = User.objects.create_user(**self.user_info)
+        new_user = get_user_model().objects.create_user(**self.user_info)
         profile = RegistrationProfile.objects.create_profile(new_user)
 
         self.assertEqual(RegistrationProfile.objects.count(), 1)
         """
         ``RegistrationProfile.send_activation_email`` sends an
         email.
-        
+
         """
-        new_user = User.objects.create_user(**self.user_info)
+        new_user = get_user_model().objects.create_user(**self.user_info)
         profile = RegistrationProfile.objects.create_profile(new_user)
         profile.send_activation_email(Site.objects.get_current())
         self.assertEqual(len(mail.outbox), 1)
         """
         Creating a new user populates the correct data, and sets the
         user's account inactive.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
     def test_user_creation_email(self):
         """
         By default, creating a new user sends an activation email.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
         """
         Passing ``send_email=False`` when creating a new user will not
         send an activation email.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     send_email=False,
         """
         ``RegistrationProfile.activation_key_expired()`` is ``False``
         within the activation window.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
         """
         ``RegistrationProfile.activation_key_expired()`` is ``True``
         outside the activation window.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
         """
         Activating a user within the permitted window makes the
         account active, and resets the activation key.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
         """
         Attempting to activate outside the permitted window does not
         activate the account.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
         self.failIf(isinstance(activated, User))
         self.failIf(activated)
 
-        new_user = User.objects.get(username='alice')
+        new_user = get_user_model().objects.get(username='alice')
         self.failIf(new_user.is_active)
 
         profile = RegistrationProfile.objects.get(user=new_user)
         """
         Attempting to activate with a key which is not a SHA1 hash
         fails.
-        
+
         """
         self.failIf(RegistrationProfile.objects.activate_user('foo'))
 
     def test_activation_already_activated(self):
         """
         Attempting to re-activate an already-activated account fails.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
         """
         Attempting to activate with a non-existent key (i.e., one not
         associated with any account) fails.
-        
+
         """
         # Due to the way activation keys are constructed during
         # registration, this will never be a valid key.
         """
         ``RegistrationProfile.objects.delete_expired_users()`` only
         deletes inactive users whose activation window has expired.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
 
         RegistrationProfile.objects.delete_expired_users()
         self.assertEqual(RegistrationProfile.objects.count(), 1)
-        self.assertRaises(User.DoesNotExist, User.objects.get, username='bob')
+        self.assertRaises(User.DoesNotExist, get_user_model().objects.get, username='bob')
 
     def test_management_command(self):
         """
         The ``cleanupregistration`` management command properly
         deletes expired accounts.
-        
+
         """
         new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                     **self.user_info)
 
         management.call_command('cleanupregistration')
         self.assertEqual(RegistrationProfile.objects.count(), 1)
-        self.assertRaises(User.DoesNotExist, User.objects.get, username='bob')
+        self.assertRaises(User.DoesNotExist, get_user_model().objects.get, username='bob')

registration/tests/simple_backend.py

 from django.conf import settings
-from django.contrib.auth.models import User
 from django.core.urlresolvers import reverse
 from django.test import TestCase
 
+from registration.compat import get_user_model
 from registration.forms import RegistrationForm
 
 
         """
         The setting ``REGISTRATION_OPEN`` appropriately controls
         whether registration is permitted.
-        
+
         """
         old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
         settings.REGISTRATION_OPEN = True
         # the 'registration is closed' message.
         resp = self.client.get(reverse('registration_register'))
         self.assertRedirects(resp, reverse('registration_disallowed'))
-        
+
         resp = self.client.post(reverse('registration_register'),
                                 data={'username': 'bob',
                                       'email': 'bob@example.com',
         """
         HTTP ``GET`` to the registration view uses the appropriate
         template and populates a registration form into the context.
-        
+
         """
         resp = self.client.get(reverse('registration_register'))
         self.assertEqual(200, resp.status_code)
                                       'password1': 'secret',
                                       'password2': 'secret'})
 
-        new_user = User.objects.get(username='bob')
+        new_user = get_user_model().objects.get(username='bob')
         self.assertEqual(302, resp.status_code)
         self.failUnless(new_user.get_absolute_url() in resp['Location'])
 
     def test_registration_failure(self):
         """
         Registering with invalid data fails.
-        
+
         """
         resp = self.client.post(reverse('registration_register'),
                                 data={'username': 'bob',