desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check and clean the Chilean RUT.'
def clean(self, value):
super(CLRutField, self).clean(value) if (value in EMPTY_VALUES): return u'' (rut, verificador) = self._canonify(value) if (self._algorithm(rut) == verificador): return self._format(rut, verificador) else: raise ValidationError(self.error_messages['checksum'])
'Takes RUT in pure canonical form, calculates the verifier digit.'
def _algorithm(self, rut):
suma = 0 multi = 2 for r in rut[::(-1)]: suma += (int(r) * multi) multi += 1 if (multi == 8): multi = 2 return u'0123456789K0'[(11 - (suma % 11))]
'Turns the RUT into one normalized format. Returns a (rut, verifier) tuple.'
def _canonify(self, rut):
rut = smart_unicode(rut).replace(' ', '').replace('.', '').replace('-', '') return (rut[:(-1)], rut[(-1)].upper())
'Formats the RUT from canonical form to the common string representation. If verifier=None, then the last digit in \'code\' is the verifier.'
def _format(self, code, verifier=None):
if (verifier is None): verifier = code[(-1)] code = code[:(-1)] while ((len(code) > 3) and ('.' not in code[:3])): pos = code.find('.') if (pos == (-1)): new_dot = (-3) else: new_dot = (pos - 3) code = ((code[:new_dot] + '.') + code[new_dot...
'Calculates a checksum with the provided algorithm.'
def has_valid_checksum(self, number):
multiple_table = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1) result = 0 for i in range(len(number)): result += (int(number[i]) * multiple_table[i]) return ((result % 10) == 0)
'Calculates a checksum with the provided algorithm.'
def has_valid_checksum(self, number):
multiple_table = (6, 5, 7, 2, 3, 4, 5, 6, 7) result = 0 for i in range((len(number) - 1)): result += (int(number[i]) * multiple_table[i]) result %= 11 if (result == int(number[(-1)])): return True else: return False
'Calculates a checksum with the provided algorithm.'
def has_valid_checksum(self, number):
weights = ((8, 9, 2, 3, 4, 5, 6, 7, (-1)), (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8, (-1)), (8, 9, 2, 3, 4, 5, 6, 7, (-1), 0, 0, 0, 0, 0)) weights = [table for table in weights if (len(table) == len(number))] for table in weights: checksum = sum([(int(n) * w) for (n, w) in zip(number, table)]) ...
'Validate a phone number. Strips parentheses, whitespace and hyphens.'
def clean(self, value):
super(AUPhoneNumberField, self).clean(value) if (value in EMPTY_VALUES): return u'' value = re.sub('(\\(|\\)|\\s+|-)', '', smart_unicode(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: return (u'%s' % phone_match.group(1)) raise ValidationError(self.error_mess...
'A simple sitemap can be rendered'
def test_simple_sitemap(self):
response = self.client.get('/simple/sitemap.xml') self.assertEquals(response.content, ('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>\n</...
'A minimal generic sitemap can be rendered'
def test_generic_sitemap(self):
response = self.client.get('/generic/sitemap.xml') expected = '' for username in User.objects.values_list('username', flat=True): expected += ('<url><loc>%s/users/%s/</loc></url>' % (self.base_url, username)) self.assertEquals(response.content, ('<?xml version="1.0" encoding="UTF-8"?>\n<ur...
'Check we get ImproperlyConfigured when we don\'t pass a site object to Sitemap.get_urls if Site objects exists, but the sites framework is not actually installed.'
def test_sitemap_get_urls_no_site_2(self):
Site._meta.installed = False self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)
'Saves the current session data to the database. If \'must_create\' is True, a database error will be raised if the saving operation doesn\'t create a *new* entry (as opposed to possibly updating an existing entry).'
def save(self, must_create=False):
obj = Session(session_key=self.session_key, session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date()) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) e...
'Returns the given session dictionary pickled and encoded as a string.'
def encode(self, session_dict):
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) pickled_md5 = md5_constructor((pickled + settings.SECRET_KEY)).hexdigest() return base64.encodestring((pickled + pickled_md5))
'Returns session key that isn\'t being used.'
def _get_new_session_key(self):
try: pid = os.getpid() except AttributeError: pid = 1 while 1: session_key = md5_constructor(('%s%s%s%s' % (randrange(0, MAX_SESSION_KEY), pid, time.time(), settings.SECRET_KEY))).hexdigest() if (not self.exists(session_key)): break return session_key
'Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance.'
def _get_session(self, no_load=False):
self.accessed = True try: return self._session_cache except AttributeError: if ((self._session_key is None) or no_load): self._session_cache = {} else: self._session_cache = self.load() return self._session_cache
'Get the number of seconds until the session expires.'
def get_expiry_age(self):
expiry = self.get('_session_expiry') if (not expiry): return settings.SESSION_COOKIE_AGE if (not isinstance(expiry, datetime)): return expiry delta = (expiry - datetime.now()) return ((delta.days * 86400) + delta.seconds)
'Get session the expiry date (as a datetime object).'
def get_expiry_date(self):
expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if (not expiry): expiry = settings.SESSION_COOKIE_AGE return (datetime.now() + timedelta(seconds=expiry))
'Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or `...
def set_expiry(self, value):
if (value is None): try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = (datetime.now() + value) self['_session_expiry'] = value
'Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there\'s an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.'
def get_expire_at_browser_close(self):
if (self.get('_session_expiry') is None): return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return (self.get('_session_expiry') == 0)
'Removes the current session data from the database and regenerates the key.'
def flush(self):
self.clear() self.delete() self.create()
'Creates a new session key, whilst retaining the current session data.'
def cycle_key(self):
data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key)
'Returns True if the given session_key already exists.'
def exists(self, session_key):
raise NotImplementedError
'Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.'
def create(self):
raise NotImplementedError
'Saves the session data. If \'must_create\' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key.'
def save(self, must_create=False):
raise NotImplementedError
'Deletes the session data under this key. If the key is None, the current session key value is used.'
def delete(self, session_key=None):
raise NotImplementedError
'Loads the session data and returns a dictionary.'
def load(self):
raise NotImplementedError
'Get the file associated with this session key.'
def _key_to_file(self, session_key=None):
if (session_key is None): session_key = self.session_key if (not set(session_key).issubset(self.VALID_KEY_CHARS)): raise SuspiciousOperation('Invalid characters in session key') return os.path.join(self.storage_path, (self.file_prefix + session_key))
'Removes the current session data from the database and regenerates the key.'
def flush(self):
self.clear() self.delete(self.session_key) self.create()
'Returns the given session dictionary pickled and encoded as a string.'
def encode(self, session_dict):
pickled = pickle.dumps(session_dict) pickled_md5 = md5_constructor((pickled + settings.SECRET_KEY)).hexdigest() return base64.encodestring((pickled + pickled_md5))
'If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie.'
def process_response(self, request, response):
try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST): if request.session.get_e...
'Returns the current ``Site`` based on the SITE_ID in the project\'s settings. The ``Site`` object is cached the first time it\'s retrieved from the database.'
def get_current(self):
from django.conf import settings try: sid = settings.SITE_ID except AttributeError: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured('You\'re using the Django "sites framework" without having set the SITE_ID setting. ...
'Clears the ``Site`` object cache.'
def clear_cache(self):
global SITE_CACHE SITE_CACHE = {}
'Regressiontest for #12462'
def test_has_no_object_perm(self):
user = User.objects.get(username='test') content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm('auth.test', 'object'), False) ...
'A superuser has all permissions. Refs #14795'
def test_get_all_superuser_permissions(self):
user = User.objects.get(username='test2') self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all()))
'Backs up the AUTH_PROFILE_MODULE'
def setUp(self):
self.old_AUTH_PROFILE_MODULE = getattr(settings, 'AUTH_PROFILE_MODULE', None)
'Restores the AUTH_PROFILE_MODULE -- if it was not set it is deleted, otherwise the old value is restored'
def tearDown(self):
if ((self.old_AUTH_PROFILE_MODULE is None) and hasattr(settings, 'AUTH_PROFILE_MODULE')): del settings.AUTH_PROFILE_MODULE if (self.old_AUTH_PROFILE_MODULE is not None): settings.AUTH_PROFILE_MODULE = self.old_AUTH_PROFILE_MODULE
'Check that login_required is assignable to callable objects.'
def testCallable(self):
class CallableView(object, ): def __call__(self, *args, **kwargs): pass login_required(CallableView())
'Check that login_required is assignable to normal views.'
def testView(self):
def normal_view(request): pass login_required(normal_view)
'Tests requests where no remote user is specified and insures that no users get created.'
def test_no_remote_user(self):
num_users = User.objects.count() response = self.client.get('/remote_user/') self.assert_(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', REMOTE_USER=None) self.assert_(response.context['user'].is_anonymous())...
'Tests the case where the username passed in the header does not exist as a User.'
def test_unknown_user(self):
num_users = User.objects.count() response = self.client.get('/remote_user/', REMOTE_USER='newuser') self.assertEqual(response.context['user'].username, 'newuser') self.assertEqual(User.objects.count(), (num_users + 1)) User.objects.get(username='newuser') response = self.client.get('/remote_user...
'Tests the case where the username passed in the header is a valid User.'
def test_known_user(self):
User.objects.create(username='knownuser') User.objects.create(username='knownuser2') num_users = User.objects.count() response = self.client.get('/remote_user/', REMOTE_USER=self.known_user) self.assertEqual(response.context['user'].username, 'knownuser') self.assertEqual(User.objects.count(), n...
'Tests that a user\'s last_login is set the first time they make a request but not updated in subsequent requests with the same session.'
def test_last_login(self):
user = User.objects.create(username='knownuser') default_login = datetime(2000, 1, 1) user.last_login = default_login user.save() response = self.client.get('/remote_user/', REMOTE_USER=self.known_user) self.assertNotEqual(default_login, response.context['user'].last_login) user = User.objec...
'Restores settings to avoid breaking other tests.'
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.curr_middleware settings.AUTHENTICATION_BACKENDS = self.curr_auth
'Grabs username before the @ character.'
def clean_username(self, username):
return username.split('@')[0]
'Sets user\'s email address.'
def configure_user(self, user):
user.email = 'user@example.com' user.save() return user
'The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address.'
def test_known_user(self):
super(RemoteUserCustomTest, self).test_known_user() self.assertEqual(User.objects.get(username='knownuser').email, '') self.assertEqual(User.objects.get(username='knownuser2').email, '')
'The unknown user created should be configured with an email address.'
def test_unknown_user(self):
super(RemoteUserCustomTest, self).test_unknown_user() newuser = User.objects.get(username='newuser') self.assertEqual(newuser.email, 'user@example.com')
'Ensure that we can make a token and that it is valid'
def test_make_token(self):
user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) self.assertTrue(p0.check_token(user, tk1))
'Ensure that the token generated for a user created in the same request will work correctly.'
def test_10265(self):
user = User.objects.create_user('comebackkid', 'test3@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) reload = User.objects.get(username='comebackkid') tk2 = p0.make_token(reload) self.assertEqual(tk1, tk2)
'Ensure we can use the token after n days, but no greater.'
def test_timeout(self):
class Mocked(PasswordResetTokenGenerator, ): def __init__(self, today): self._today_val = today def _today(self): return self._today_val user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.mak...
'Make sure we don\'t allow overly long dates, causing a potential DoS.'
def test_date_length(self):
user = User.objects.create_user('ima1337h4x0r', 'test4@example.com', 'p4ssw0rd') p0 = PasswordResetTokenGenerator() tk1 = p0._make_token_with_timestamp(user, 175455491841851871349L) self.assertFalse(p0.check_token(user, tk1))
'Error is raised if the provided email address isn\'t currently registered'
def test_email_not_found(self):
response = self.client.get('/password_reset/') self.assertEquals(response.status_code, 200) response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'}) self.assertContains(response, 'That e-mail address doesn&#39;t have an associated user account') ...
'Email is sent if a valid email address is provided for password reset'
def test_email_found(self):
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEquals(response.status_code, 302) self.assertEquals(len(mail.outbox), 1) self.assert_(('http://' in mail.outbox[0].body))
'Logout without next_page option renders the default template'
def test_logout_default(self):
self.login() response = self.client.get('/logout/') self.assertEquals(200, response.status_code) self.assert_(('Logged out' in response.content)) self.confirm_logged_out()
'Logout with next_page option given redirects to specified resource'
def test_logout_with_next_page_specified(self):
self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assert_(response['Location'].endswith('/somewhere/')) self.confirm_logged_out()
'Logout with query string redirects to specified resource'
def test_logout_with_redirect_argument(self):
self.login() response = self.client.get('/logout/?next=/login/') self.assertEqual(response.status_code, 302) self.assert_(response['Location'].endswith('/login/')) self.confirm_logged_out()
'Logout with custom query string redirects to specified resource'
def test_logout_with_custom_redirect_argument(self):
self.login() response = self.client.get('/logout/custom_query/?follow=/somewhere/') self.assertEqual(response.status_code, 302) self.assert_(response['Location'].endswith('/somewhere/')) self.confirm_logged_out()
'Check that users can be created and can set their password'
def test_user(self):
u = User.objects.create_user('testuser', 'test@example.com', 'testpw') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) self.assertTrue(u.check_password('testpw')) u.set_unusable_password() u.save() self.assertFalse(u.check_password('testpw')) self.asser...
'Check the properties of the anonymous user'
def test_anonymous_user(self):
a = AnonymousUser() self.assertFalse(a.is_authenticated()) self.assertFalse(a.is_staff) self.assertFalse(a.is_active) self.assertFalse(a.is_superuser) self.assertEqual(a.groups.all().count(), 0) self.assertEqual(a.user_permissions.all().count(), 0)
'Check the creation and properties of a superuser'
def test_superuser(self):
super = User.objects.create_superuser('super', 'super@example.com', 'super') self.assertTrue(super.is_superuser) self.assertTrue(super.is_active) self.assertTrue(super.is_staff)
'Check the operation of the createsuperuser management command'
def test_createsuperuser_management_command(self):
new_io = StringIO() call_command('createsuperuser', interactive=False, username='joe', email='joe@somewhere.org', stdout=new_io) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = User.objects.get(username='joe') self.assertEq...
'Creates and saves a User with the given username, e-mail and password.'
def create_user(self, username, email, password=None):
now = datetime.datetime.now() try: (email_name, domain_part) = email.strip().split('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, l...
'Generates a random password with the given length and given allowed_chars'
def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
from random import choice return ''.join([choice(allowed_chars) for i in range(length)])
'Always returns False. This is a way of comparing User objects to anonymous users.'
def is_anonymous(self):
return False
'Always return True. This is a way to tell if the user has been authenticated in templates.'
def is_authenticated(self):
return True
'Returns the first_name plus the last_name, with a space in between.'
def get_full_name(self):
full_name = (u'%s %s' % (self.first_name, self.last_name)) return full_name.strip()
'Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes.'
def check_password(self, raw_password):
if ('$' not in self.password): is_correct = (self.password == get_hexdigest('md5', '', raw_password)) if is_correct: self.set_password(raw_password) self.save() return is_correct return check_password(raw_password, self.password)
'Returns a list of permission strings that this user has through his/her groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned.'
def get_group_permissions(self, obj=None):
permissions = set() for backend in auth.get_backends(): if hasattr(backend, 'get_group_permissions'): if (obj is not None): if backend.supports_object_permissions: permissions.update(backend.get_group_permissions(self, obj)) else: ...
'Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific objec...
def has_perm(self, perm, obj=None):
if (not self.is_active): return False if self.is_superuser: return True return _user_has_perm(self, perm, obj)
'Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object.'
def has_perms(self, perm_list, obj=None):
for perm in perm_list: if (not self.has_perm(perm, obj)): return False return True
'Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above.'
def has_module_perms(self, app_label):
if (not self.is_active): return False if self.is_superuser: return True return _user_has_module_perms(self, app_label)
'Sends an e-mail to this User.'
def email_user(self, subject, message, from_email=None):
from django.core.mail import send_mail send_mail(subject, message, from_email, [self.email])
'Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles.'
def get_profile(self):
if (not hasattr(self, '_profile_cache')): from django.conf import settings if (not getattr(settings, 'AUTH_PROFILE_MODULE', False)): raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MODULE in your project settings') try: (app_label, ...
'Returns a set of permission strings that this user has through his/her groups.'
def get_group_permissions(self, user_obj):
if (not hasattr(user_obj, '_group_perm_cache')): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = Permission.objects.filter(group__user=user_obj) perms = perms.values_list('content_type__app_label', 'codename').order_by() user_obj._grou...
'Returns True if user_obj has any permissions in the given app_label.'
def has_module_perms(self, user_obj, app_label):
for perm in self.get_all_permissions(user_obj): if (perm[:perm.index('.')] == app_label): return True return False
'The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Returns None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found i...
def authenticate(self, remote_user):
if (not remote_user): return user = None username = self.clean_username(remote_user) if self.create_unknown_user: (user, created) = User.objects.get_or_create(username=username) if created: user = self.configure_user(user) else: try: user = Use...
'Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, returns the username unchanged.'
def clean_username(self, username):
return username
'Configures a user after creation and returns the updated user. By default, returns the user unmodified.'
def configure_user(self, user):
return user
'Use special form during user creation'
def get_form(self, request, obj=None, **kwargs):
defaults = {} if (obj is None): defaults.update({'form': self.add_form, 'fields': admin.util.flatten_fieldsets(self.add_fieldsets)}) defaults.update(kwargs) return super(UserAdmin, self).get_form(request, obj, **defaults)
'Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow.'
def response_add(self, request, obj, post_url_continue='../%s/'):
if ('_addanother' not in request.POST): request.POST['_continue'] = 1 return super(UserAdmin, self).response_add(request, obj, post_url_continue)
'If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation.'
def __init__(self, request=None, *args, **kwargs):
self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs)
'Validates that a user exists with the given e-mail address.'
def clean_email(self):
email = self.cleaned_data['email'] self.users_cache = User.objects.filter(email__iexact=email) if (len(self.users_cache) == 0): raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?")) re...
'Generates a one-use only link for resetting password and sends to the user'
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, request=None):
from django.core.mail import send_mail for user in self.users_cache: if (not domain_override): current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override t ...
'Validates that the old_password field is correct.'
def clean_old_password(self):
old_password = self.cleaned_data['old_password'] if (not self.user.check_password(old_password)): raise forms.ValidationError(_('Your old password was entered incorrectly. Please enter it again.')) return old_password
'Saves the new password.'
def save(self, commit=True):
self.user.set_password(self.cleaned_data['password1']) if commit: self.user.save() return self.user
'Returns a token that can be used once to do a password reset for the given user.'
def make_token(self, user):
return self._make_token_with_timestamp(user, self._num_days(self._today()))
'Check that a password reset token is correct for a given user.'
def check_token(self, user, token):
try: (ts_b36, hash) = token.split('-') except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False if (self._make_token_with_timestamp(user, ts) != token): return False if ((self._num_days(self._today()) - ts) > settings...
'Allows the backend to clean the username, if the backend defines a clean_username method.'
def clean_username(self, username, request):
backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) try: username = backend.clean_username(username) except AttributeError: pass return username
'Start a new wizard with a list of forms. form_list should be a list of Form classes (not instances).'
def __init__(self, form_list, initial=None):
self.form_list = form_list[:] self.initial = (initial or {}) self.extra_context = {} self.step = 0
'Helper method that returns the Form instance for the given step.'
def get_form(self, step, data=None):
return self.form_list[step](data, prefix=self.prefix_for_step(step), initial=self.initial.get(step, None))
'Helper method that returns the number of steps.'
def num_steps(self):
return len(self.form_list)
'Main method that does all the hard work, conforming to the Django view interface.'
@method_decorator(csrf_protect) def __call__(self, request, *args, **kwargs):
if ('extra_context' in kwargs): self.extra_context.update(kwargs['extra_context']) current_step = self.determine_step(request, *args, **kwargs) self.parse_params(request, *args, **kwargs) if (current_step >= self.num_steps()): raise Http404(('Step %s does not exist' % current...
'Renders the given Form object, returning an HttpResponse.'
def render(self, form, request, step, context=None):
old_data = request.POST prev_fields = [] if old_data: hidden = forms.HiddenInput() for i in range(step): old_form = self.get_form(i, old_data) hash_name = ('hash_%s' % i) prev_fields.extend([bf.as_hidden() for bf in old_form]) prev_fields.appen...
'Given the step, returns a Form prefix to use.'
def prefix_for_step(self, step):
return str(step)
'Hook for rendering a template if a hash check failed. step is the step that failed. Any previous step is guaranteed to be valid. This default implementation simply renders the form for the given step, but subclasses may want to display an error message, etc.'
def render_hash_failure(self, request, step):
return self.render(self.get_form(step), request, step, context={'wizard_error': _('We apologize, but your form has expired. Please continue filling out the form from this page.')})
'Hook for rendering a template if final revalidation failed. It is highly unlikely that this point would ever be reached, but See the comment in __call__() for an explanation.'
def render_revalidation_failure(self, request, step, form):
return self.render(form, request, step)
'Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address.'
def security_hash(self, request, form):
return security_hash(request, form)
'Given the request object and whatever *args and **kwargs were passed to __call__(), returns the current step (which is zero-based). Note that the result should not be trusted. It may even be a completely invalid number. It\'s not the job of this method to validate it.'
def determine_step(self, request, *args, **kwargs):
if (not request.POST): return 0 try: step = int(request.POST.get(self.step_field_name, 0)) except ValueError: return 0 return step
'Hook for setting some state, given the request object and whatever *args and **kwargs were passed to __call__(), sets some state. This is called at the beginning of __call__().'
def parse_params(self, request, *args, **kwargs):
pass
'Hook for specifying the name of the template to use for a given step. Note that this can return a tuple of template names if you\'d like to use the template system\'s select_template() hook.'
def get_template(self, step):
return 'forms/wizard.html'