Commits

tejinderss committed 7934696

Making backward incompatible changes

  • Participants
  • Parent commits 592660a

Comments (0)

Files changed (10)

 
 * First packaged version using distutils.
 
-* Added docs/ directory and overview. 
+* Added docs/ directory and overview.
 Mercurial checkout.
 
 Note that this application requires Python 2.5 or later, and a
-functional installation of Django 1.4 or newer. You can obtain Python
+functional installation of Django 1.5 or newer. You can obtain Python
 from http://www.python.org/ and Django from
 http://www.djangoproject.com/.

File registration/backends/default/views.py

     an instance of ``registration.models.RegistrationProfile``. See
     that model and its custom manager for full documentation of its
     fields and supported operations.
-    
+
     """
     def register(self, request, **cleaned_data):
         """
 
         * If ``REGISTRATION_OPEN`` is both specified and set to
           ``False``, registration is not permitted.
-        
+
         """
         return getattr(settings, 'REGISTRATION_OPEN', True)
 
         """
         Return the name of the URL to redirect to after successful
         user registration.
-        
+
         """
         return ('registration_complete', (), {})
 
         ``registration.signals.user_activated`` will be sent, with the
         newly activated ``User`` as the keyword argument ``user`` and
         the class of this backend as the sender.
-        
+
         """
         activated_user = RegistrationProfile.objects.activate_user(activation_key)
         if activated_user:

File 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 django.contrib.auth import get_user_model
 
 from registration import signals
 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)
 

File registration/forms.py

 """
 
 
-from django.contrib.auth.models import User
+from django.contrib.auth import get_user_model
 from django import forms
 from django.utils.translation import ugettext_lazy as _
 
 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"),
                                 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']):
+        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:

File registration/models.py

 import re
 
 from django.conf import settings
+from django.contrib.auth import get_user_model
 from django.db import models
 from django.db import transaction
 from django.template.loader import render_to_string
 
 
 SHA1_RE = re.compile('^[a-f0-9]{40}$')
-User = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
+USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
 
 
 class RegistrationManager(models.Manager):
         user. To disable this, pass ``send_email=False``.
 
         """
-        new_user = User.objects.create_user(username, email, password)
+        new_user = get_user_model().objects.create_user(username, email, password)
         new_user.is_active = False
         new_user.save()
 
                     if not user.is_active:
                         user.delete()
                         profile.delete()
-            except User.DoesNotExist:
+            except get_user_model().DoesNotExist:
                 profile.delete()
 
+
 class RegistrationProfile(models.Model):
     """
     A simple profile which stores an activation key for use during
     """
     ACTIVATED = u"ALREADY_ACTIVATED"
 
-    user = models.ForeignKey(User, unique=True, verbose_name=_('user'))
+    user = models.ForeignKey(USER_MODEL, unique=True, verbose_name=_('user'))
     activation_key = models.CharField(_('activation key'), max_length=40)
 
     objects = RegistrationManager()

File registration/tests/default_backend.py

 import datetime
 
 from django.conf import settings
-from django.contrib.auth.models import User
+from django.contrib.auth import get_user_model
 from django.contrib.sites.models import Site
 from django.core import mail
 from django.core.urlresolvers import reverse
         # 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',

File registration/tests/forms.py

-from django.contrib.auth.models import User
+from django.contrib.auth import get_user_model
 from django.test import TestCase
 
 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',

File registration/tests/models.py

 import re
 
 from django.conf import settings
-from django.contrib.auth.models import User
+from django.contrib.auth import get_user_model
 from django.contrib.sites.models import Site
 from django.core import mail
 from django.core import management
 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)
         profile = RegistrationProfile.objects.get(user=new_user)
         activated = RegistrationProfile.objects.activate_user(profile.activation_key)
 
-        self.failUnless(isinstance(activated, User))
+        self.failUnless(isinstance(activated, get_user_model()))
         self.assertEqual(activated.id, new_user.id)
         self.failUnless(activated.is_active)
 
         """
         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)
         profile = RegistrationProfile.objects.get(user=new_user)
         activated = RegistrationProfile.objects.activate_user(profile.activation_key)
 
-        self.failIf(isinstance(activated, User))
+        self.failIf(isinstance(activated, get_user_model()))
         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(get_user_model().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(get_user_model().DoesNotExist, get_user_model().objects.get, username='bob')

File registration/tests/simple_backend.py

 from django.conf import settings
-from django.contrib.auth.models import User
+from django.contrib.auth import get_user_model
 from django.core.urlresolvers import reverse
 from django.test import TestCase
 
         """
         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',