def test_password_verification(self): # The two new passwords do not match. user = User.objects.get(username='******') data = { 'new_password1': 'abc123', 'new_password2': 'abc', } form = SetPasswordForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual( form["new_password2"].errors, [force_unicode(form.error_messages['password_mismatch'])])
def test_password_verification(self): # The verification password is incorrect. data = { 'username': '******', 'password1': 'test123', 'password2': 'test', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form["password2"].errors, [force_unicode(form.error_messages['password_mismatch'])])
def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, type='checkbox', name=name) try: result = self.check_test(value) except: # Silently catch exceptions result = False if result: final_attrs['checked'] = 'checked' if not (value is True or value is False or value is None or value == ''): # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def test_incorrect_password(self): user = User.objects.get(username='******') data = { 'old_password': '******', 'new_password1': 'abc123', 'new_password2': 'abc123', } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) self.assertEqual( form["old_password"].errors, [force_unicode(form.error_messages['password_incorrect'])])
def label_tag(self): classes = [] contents = conditional_escape(force_unicode(self.field.label)) if self.is_checkbox: classes.append(u'vCheckboxLabel') else: contents += u':' if self.field.field.required: classes.append(u'required') if not self.is_first: classes.append(u'inline') attrs = classes and {'class': u' '.join(classes)} or {} return self.field.label_tag(contents=mark_safe(contents), attrs=attrs)
def test_inactive_user_i18n(self): with self.settings(USE_I18N=True): with translation.override('pt-br', deactivate=True): # The user is inactive. data = { 'username': '******', 'password': '******', } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual( form.non_field_errors(), [force_unicode(form.error_messages['inactive'])])
def handle_file_complete(self, old_field_name, counters): """ Handle all the signalling that takes place when a file is complete. """ for i, handler in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: # If it returns a file object, then set the files dict. self._files.appendlist(force_unicode(old_field_name, self._encoding, errors='replace'), file_obj) break
def __unicode__(self): # self.name is deprecated in favor of using model's verbose_name, which # can be translated. Formal deprecation is delayed until we have DB # migration to be able to remove the field from the database along with # the attribute. # # We return self.name only when users have changed its value from the # initial verbose_name_raw and might rely on it. model = self.model_class() if not model or self.name != model._meta.verbose_name_raw: return self.name else: return force_unicode(model._meta.verbose_name)
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) id_ = final_attrs.get('id', None) inputs = [] for i, v in enumerate(value): input_attrs = dict(value=force_unicode(v), **final_attrs) if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. input_attrs['id'] = '%s_%s' % (id_, i) inputs.append(u'<input%s />' % flatatt(input_attrs)) return mark_safe(u'\n'.join(inputs))
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = force_unicode(base) paths = [force_unicode(p) for p in paths] final_path = abspathu(join(base, *paths)) base_path = abspathu(base) base_path_len = len(base_path) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows) # and that the next character after the final path is os.sep (or nothing, # in which case final_path must be equal to base_path). if not normcase(final_path).startswith(normcase(base_path)) \ or final_path[base_path_len:base_path_len+1] not in ('', sep): raise ValueError('The joined path (%s) is located outside of the base ' 'path component (%s)' % (final_path, base_path)) return final_path
def __init__(self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs): to_unicode = lambda s: force_unicode(s, strings_only=True) if categories: categories = [force_unicode(c) for c in categories] if ttl is not None: # Force ints to unicode ttl = force_unicode(ttl) self.feed = { 'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'language': to_unicode(language), 'author_email': to_unicode(author_email), 'author_name': to_unicode(author_name), 'author_link': iri_to_uri(author_link), 'subtitle': to_unicode(subtitle), 'categories': categories or (), 'feed_url': iri_to_uri(feed_url), 'feed_copyright': to_unicode(feed_copyright), 'id': feed_guid or link, 'ttl': ttl, } self.feed.update(kwargs) self.items = []
def get_script_name(environ): """ Returns the equivalent of the HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite has been used, returns what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything). """ from my_django.conf import settings if settings.FORCE_SCRIPT_NAME is not None: return force_unicode(settings.FORCE_SCRIPT_NAME) # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every Web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = environ.get('SCRIPT_URL', u'') if not script_url: script_url = environ.get('REDIRECT_URL', u'') if script_url: return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))]) return force_unicode(environ.get('SCRIPT_NAME', u''))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [u'<ul>'] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label)) output.append(u'</ul>') return mark_safe(u'\n'.join(output))
def save(self, name, content): """ Saves new content to the file specified by name. The content should be a proper File object, ready to be read from the beginning. """ # Get the proper name for the file, as it will actually be saved. if name is None: name = content.name name = self.get_available_name(name) name = self._save(name, content) # Store filenames with forward slashes, even on Windows return force_unicode(name.replace('\\', '/'))
def _render_value_in_context(value, context): """ Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated. """ value = localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=context.use_l10n) value = force_unicode(value) if ((context.autoescape and not isinstance(value, SafeData)) or isinstance(value, EscapeData)): return escape(value) else: return value
def add_truncation_text(self, text, truncate=None): if truncate is None: truncate = pgettext('String to return when truncating text', u'%(truncated_text)s...') truncate = force_unicode(truncate) if '%(truncated_text)s' in truncate: return truncate % {'truncated_text': text} # The truncation text didn't contain the %(truncated_text)s string # replacement argument so just append it to the text. if text.endswith(truncate): # But don't append the truncation text if the current text already # ends in this. return text return '%s%s' % (text, truncate)
def regex(self): """ Returns a compiled regular expression, depending upon the activated language-code. """ language_code = get_language() if language_code not in self._regex_dict: if isinstance(self._regex, basestring): compiled_regex = re.compile(self._regex, re.UNICODE) else: regex = force_unicode(self._regex) compiled_regex = re.compile(regex, re.UNICODE) self._regex_dict[language_code] = compiled_regex return self._regex_dict[language_code]
def _i18n_cache_key_suffix(request, cache_key): """If necessary, adds the current locale or time zone to the cache key.""" if settings.USE_I18N or settings.USE_L10N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language # which in turn can also fall back to settings.LANGUAGE_CODE cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language()) if settings.USE_TZ: # The datetime module doesn't restrict the output of tzname(). # Windows is known to use non-standard, locale-dependant names. # User-defined tzinfo classes may return absolutely anything. # Hence this paranoid conversion to create a valid cache key. tz_name = force_unicode(get_current_timezone_name(), errors='ignore') cache_key += '.%s' % tz_name.encode('ascii', 'ignore').replace(' ', '_') return cache_key
def test_both_passwords(self): # One (or both) passwords weren't given data = {'username': '******'} form = UserCreationForm(data) required_error = [ force_unicode(Field.default_error_messages['required']) ] self.assertFalse(form.is_valid()) self.assertEqual(form['password1'].errors, required_error) self.assertEqual(form['password2'].errors, required_error) data['password2'] = 'test123' form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form['password1'].errors, required_error)
def clean(self, value): if self.required and not value: raise ValidationError(self.error_messages['required']) elif not self.required and not value: return [] if not isinstance(value, (list, tuple)): raise ValidationError(self.error_messages['list']) key = self.to_field_name or 'pk' for pk in value: try: self.queryset.filter(**{key: pk}) except ValueError: raise ValidationError(self.error_messages['invalid_pk_value'] % pk) qs = self.queryset.filter(**{'%s__in' % key: value}) pks = set([force_unicode(getattr(o, key)) for o in qs]) for val in value: if force_unicode(val) not in pks: raise ValidationError(self.error_messages['invalid_choice'] % val) # Since this overrides the inherited ModelChoiceField.clean # we run custom validators here self.run_validators(value) return qs
def label_for_field(name, model, model_admin=None, return_attr=False): """ Returns a sensible label for a field name. The name can be a callable or the name of an object attributes, as well as a genuine fields. If return_attr is True, the resolved attribute (which could be a callable) is also returned. This will be None if (and only if) the name refers to a field. """ attr = None try: field = model._meta.get_field_by_name(name)[0] if isinstance(field, RelatedObject): label = field.opts.verbose_name else: label = field.verbose_name except models.FieldDoesNotExist: if name == "__unicode__": label = force_unicode(model._meta.verbose_name) attr = unicode elif name == "__str__": label = smart_str(model._meta.verbose_name) attr = str else: if callable(name): attr = name elif model_admin is not None and hasattr(model_admin, name): attr = getattr(model_admin, name) elif hasattr(model, name): attr = getattr(model, name) else: message = "Unable to lookup '%s' on %s" % ( name, model._meta.object_name) if model_admin: message += " or %s" % (model_admin.__class__.__name__, ) raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif callable(attr): if attr.__name__ == "<lambda>": label = "--" else: label = pretty_name(attr.__name__) else: label = pretty_name(name) if return_attr: return (label, attr) else: return label
def get_date_list(self, queryset, date_type): """ Get a date list by calling `queryset.dates()`, checking along the way for empty lists that aren't allowed. """ date_field = self.get_date_field() allow_empty = self.get_allow_empty() date_list = queryset.dates(date_field, date_type)[::-1] if date_list is not None and not date_list and not allow_empty: name = force_unicode(queryset.model._meta.verbose_name_plural) raise Http404( _(u"No %(verbose_name_plural)s available") % {'verbose_name_plural': name}) return date_list
def sanitize_address(addr, encoding): if isinstance(addr, basestring): addr = parseaddr(force_unicode(addr)) nm, addr = addr nm = str(Header(nm, encoding)) try: addr = addr.encode('ascii') except UnicodeEncodeError: # IDN if u'@' in addr: localpart, domain = addr.split(u'@', 1) localpart = str(Header(localpart, encoding)) domain = domain.encode('idna') addr = '@'.join([localpart, domain]) else: addr = str(Header(addr, encoding)) return formataddr((nm, addr))
def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.root_query_set = model_admin.queryset(request) self.list_display = list_display self.list_display_links = list_display_links self.list_filter = list_filter self.date_hierarchy = date_hierarchy self.search_fields = search_fields self.list_select_related = list_select_related self.list_per_page = list_per_page self.list_max_show_all = list_max_show_all self.model_admin = model_admin # Get search parameters from the query string. try: self.page_num = int(request.GET.get(PAGE_VAR, 0)) except ValueError: self.page_num = 0 self.show_all = ALL_VAR in request.GET self.is_popup = IS_POPUP_VAR in request.GET self.to_field = request.GET.get(TO_FIELD_VAR) self.params = dict(request.GET.items()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] if self.is_popup: self.list_editable = () else: self.list_editable = list_editable self.query = request.GET.get(SEARCH_VAR, '') self.query_set = self.get_query_set(request) self.get_results(request) if self.is_popup: title = ugettext('Select %s') else: title = ugettext('Select %s to change') self.title = title % force_unicode(self.opts.verbose_name) self.pk_attname = self.lookup_opts.pk.attname
def convert_values(self, value, field): if isinstance(value, Database.LOB): value = value.read() if field and field.get_internal_type() == 'TextField': value = force_unicode(value) # Oracle stores empty strings as null. We need to undo this in # order to adhere to the Django convention of using the empty # string instead of null, but only if the field accepts the # empty string. if value is None and field and field.empty_strings_allowed: value = u'' # Convert 1 or 0 to True or False elif value in (1, 0) and field and field.get_internal_type() in ( 'BooleanField', 'NullBooleanField'): value = bool(value) # Force floats to the correct type elif value is not None and field and field.get_internal_type( ) == 'FloatField': value = float(value) # Convert floats to decimals elif value is not None and field and field.get_internal_type( ) == 'DecimalField': value = util.typecast_decimal(field.format_number(value)) # cx_Oracle always returns datetime.datetime objects for # DATE and TIMESTAMP columns, but Django wants to see a # python datetime.date, .time, or .datetime. We use the type # of the Field to determine which to cast to, but it's not # always available. # As a workaround, we cast to date if all the time-related # values are 0, or to time if the date is 1/1/1900. # This could be cleaned a bit by adding a method to the Field # classes to normalize values from the database (the to_python # method is used for validation and isn't what we want here). elif isinstance(value, Database.Timestamp): if field and field.get_internal_type() == 'DateTimeField': pass elif field and field.get_internal_type() == 'DateField': value = value.date() elif field and field.get_internal_type() == 'TimeField' or ( value.year == 1900 and value.month == value.day == 1): value = value.time() elif value.hour == value.minute == value.second == value.microsecond == 0: value = value.date() return value
def smart_split(text): r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then be further processed with unescape_string_literal()). >>> list(smart_split(r'This is "a person\'s" test.')) [u'This', u'is', u'"a person\\\'s"', u'test.'] >>> list(smart_split(r"Another 'person\'s' test.")) [u'Another', u"'person\\'s'", u'test.'] >>> list(smart_split(r'A "\"funky\" style" test.')) [u'A', u'"\\"funky\\" style"', u'test.'] """ text = force_unicode(text) for bit in smart_split_re.finditer(text): yield bit.group(0)
def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ return dict( content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_unicode(self.target_object._get_pk_val()), user_name=self.cleaned_data["name"], user_email=self.cleaned_data["email"], user_url=self.cleaned_data["url"], comment=self.cleaned_data["comment"], submit_date=timezone.now(), site_id=settings.SITE_ID, is_public=True, is_removed=False, )
def append(self, element): if isinstance(element, basestring): element = force_unicode(element) element = normalize_whitespace(element) if self.children: if isinstance(self.children[-1], basestring): self.children[-1] += element self.children[-1] = normalize_whitespace(self.children[-1]) return elif self.children: # removing last children if it is only whitespace # this can result in incorrect dom representations since # whitespace between inline tags like <span> is significant if isinstance(self.children[-1], basestring): if self.children[-1].isspace(): self.children.pop() if element: self.children.append(element)
def smart_urlquote(url): "Quotes a URL if it isn't already quoted." # Handle IDN before quoting. scheme, netloc, path, query, fragment = urlparse.urlsplit(url) try: netloc = netloc.encode('idna') # IDN -> ACE except UnicodeError: # invalid domain part pass else: url = urlparse.urlunsplit((scheme, netloc, path, query, fragment)) # An URL is considered unquoted if it contains no % characters or # contains a % not followed by two hexadecimal digits. See #9655. if '%' not in url or unquoted_percents_re.search(url): # See http://bugs.python.org/issue2637 url = urllib.quote(smart_str(url), safe='!*\'();:@&=+$,/?#[]~') return force_unicode(url)
def intcomma(value, use_l10n=True): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ if settings.USE_L10N and use_l10n: try: if not isinstance(value, float): value = int(value) except (TypeError, ValueError): return intcomma(value, False) else: return number_format(value, force_grouping=True) orig = force_unicode(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) if orig == new: return new else: return intcomma(new, use_l10n)