def test_store(self): self.assertEqual(self.config.INT_VALUE, 1) self.assertEqual(self.config.LONG_VALUE, long(123456)) self.assertEqual(self.config.BOOL_VALUE, True) self.assertEqual(self.config.STRING_VALUE, 'Hello world') self.assertEqual(self.config.UNICODE_VALUE, six.u('Rivière-Bonjour')) self.assertEqual(self.config.DECIMAL_VALUE, Decimal('0.1')) self.assertEqual(self.config.DATETIME_VALUE, datetime(2010, 8, 23, 11, 29, 24)) self.assertEqual(self.config.FLOAT_VALUE, 3.1415926536) self.assertEqual(self.config.DATE_VALUE, date(2010, 12, 24)) self.assertEqual(self.config.TIME_VALUE, time(23, 59, 59)) # set values self.config.INT_VALUE = 100 self.config.LONG_VALUE = long(654321) self.config.BOOL_VALUE = False self.config.STRING_VALUE = 'Beware the weeping angel' self.config.UNICODE_VALUE = six.u('Québec') self.config.DECIMAL_VALUE = Decimal('1.2') self.config.DATETIME_VALUE = datetime(1977, 10, 2) self.config.FLOAT_VALUE = 2.718281845905 self.config.DATE_VALUE = date(2001, 12, 20) self.config.TIME_VALUE = time(1, 59, 0) # read again self.assertEqual(self.config.INT_VALUE, 100) self.assertEqual(self.config.LONG_VALUE, long(654321)) self.assertEqual(self.config.BOOL_VALUE, False) self.assertEqual(self.config.STRING_VALUE, 'Beware the weeping angel') self.assertEqual(self.config.UNICODE_VALUE, six.u('Québec')) self.assertEqual(self.config.DECIMAL_VALUE, Decimal('1.2')) self.assertEqual(self.config.DATETIME_VALUE, datetime(1977, 10, 2)) self.assertEqual(self.config.FLOAT_VALUE, 2.718281845905) self.assertEqual(self.config.DATE_VALUE, date(2001, 12, 20)) self.assertEqual(self.config.TIME_VALUE, time(1, 59, 0))
def get_cache_key(user_or_username, size, prefix): """ Returns a cache key consisten of a username and image size. """ if isinstance(user_or_username, get_user_model()): user_or_username = get_username(user_or_username) key = six.u("%s_%s_%s") % (prefix, user_or_username, size) return six.u("%s_%s") % (slugify(key)[:100], hashlib.md5(force_bytes(key)).hexdigest())
def create_year_overrides_for(year): """ Creates the year overrides for a certain year """ parent_tag = Es.id_by_name('!year-overrides') Es.ecol.insert({ 'humanNames': [{six.u('human'): six.u('Wel jaar {}').format(year)}], 'tags': [parent_tag], 'types': ['tag'], 'year-override': {'type': True, 'year': year}}) Es.ecol.insert({ 'humanNames': [{six.u('human'): six.u('Niet jaar {}').format(year)}], 'tags': [parent_tag], 'types': ['tag'], 'year-override': {'type': False, 'year': year}})
def render(self, name, value, attrs=None, choices=()): if not value: self.choices = () else: self.choices = [(x.pk, six.u(x)) for x in Country.objects.filter(pk=value)] attrs['readonly'] = 'readonly' return super(CountryWidget, self).render(name, value, attrs, ())
def infer_csv(csv_file, outfile, row_limit=0): with io.open(outfile, 'w') as fp: with io.open(csv_file) as stream: headers = stream.readline().rstrip('\n').split(',') values = jsontableschema.compat.csv_reader(stream) schema = jsontableschema.infer(headers, values, row_limit=row_limit) fp.write(six.u(json.dumps(schema, indent=2, ensure_ascii=False)))
def test_get_with_filter_unicode(self): User.objects.create( name=UNICODE_STRING, last_name='Unicode' ) with self.assertNumQueries(1): response = self.client.get( '/users/?filter{name}[]=%s' % UNICODE_URL_STRING ) self.assertEquals(200, response.status_code) self.assertEquals( 1, len( json.loads( response.content.decode('utf-8') )['users'] ) ) with self.assertNumQueries(1): response = self.client.get( six.u('/users/?filter{name}[]=%s') % UNICODE_STRING ) self.assertEquals(200, response.status_code) self.assertEquals( 1, len( json.loads( response.content.decode('utf-8') )['users'] ) )
def __unicode__(self): try: user = self.user except ObjectDoesNotExist: user = None return six.u("{0} ({1})".format(self.name, user))
def test_ng_length(self): first_name = self.dom('input[name=first_name]') self.assertEqual(len(first_name), 1) attrib = dict(first_name[0].attrib.items()) self.assertDictContainsSubset({'ng-required': 'true'}, attrib) self.assertDictContainsSubset({'ng-minlength': '3'}, attrib) self.assertDictContainsSubset({'ng-maxlength': '20'}, attrib) lis = self.dom('label[for=id_first_name]').closest('th').next('td').children('ul.djng-field-errors > li') if VERSION[1] == 5: # Django < 1.6 not not know about minlength and maxlength self.assertEqual(len(lis), 2) else: self.assertEqual(len(lis), 4) attrib = dict(lis[0].attrib.items()) self.assertDictContainsSubset({'ng-show': self.form_name + six.u('[\'first_name\'].$error.required')}, attrib) attrib = dict(lis[1].attrib.items()) self.assertDictContainsSubset({'ng-show': self.form_name + six.u('[\'first_name\'].$error.minlength')}, attrib)
def render(self, name, value, attrs=None): if attrs is None: attrs = {} #output = [super(ForeignKeySearchInput, self).render(name, value, attrs)] opts = self.rel.to._meta app_label = opts.app_label model_name = opts.object_name.lower() related_url = '../../../%s/%s/' % (app_label, model_name) params = self.url_parameters() if params: url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in params.items()]) else: url = '' if not 'class' in attrs: attrs['class'] = 'vForeignKeyRawIdAdminField' # Call the TextInput render method directly to have more control output = [forms.TextInput.render(self, name, value, attrs)] if value: label = self.label_for_value(value) else: label = six.u('') try: admin_media_prefix = settings.ADMIN_MEDIA_PREFIX except AttributeError: admin_media_prefix = settings.STATIC_URL + "admin/" context = { 'url': url, 'related_url': related_url, 'admin_media_prefix': admin_media_prefix, 'search_path': self.search_path, 'search_fields': ','.join(self.search_fields), 'model_name': model_name, 'app_label': app_label, 'label': label, 'name': name, 'pre_django_14': (django.VERSION[:2] < (1, 4)), } output.append(render_to_string(self.widget_template or ( 'django_extensions/widgets/%s/%s/foreignkey_searchinput.html' % (app_label, model_name), 'django_extensions/widgets/%s/foreignkey_searchinput.html' % app_label, 'django_extensions/widgets/foreignkey_searchinput.html', ), context)) output.reverse() return mark_safe(six.u(''.join(output)))
def register(audit_obj, description, operation=None): audit = Audit() audit.operation = Audit.CHANGE if operation is None else operation audit.content_object = audit_obj audit.description = description audit.obj_description = (audit_obj and u(audit_obj) and '')[:100] audit.audit_request = AuditRequest.current_request(True) audit.save() return audit
def to_python(self, value): if isinstance(value, six.string_types) and value: try: return json.loads(value) except ValueError as exc: raise forms.ValidationError( 'JSON decode error: %s' % (six.u(exc.args[0]),) ) else: return value
def audit_content(self, audit): obj_string = audit.obj_description or u(audit.content_object) return "<a title='%(filter)s' href='%(base)s?content_type__id__exact=%(type_id)s&object_id__exact=%(id)s'>%(type)s: %(obj)s</a>" % { 'filter': _("Click to filter"), 'base': reverse('admin:simple_audit_audit_changelist'), 'type': audit.content_type, 'type_id': audit.content_type.id, 'obj': obj_string, 'id': audit.object_id}
def deconstruct(self): name, path, args, kwargs = super(AutoSlugField, self).deconstruct() kwargs['populate_from'] = self._populate_from if not self.separator == six.u('-'): kwargs['separator'] = self.separator if self.overwrite is not False: kwargs['overwrite'] = True if self.allow_duplicates is not False: kwargs['allow_duplicates'] = True return name, path, args, kwargs
def test_missing_values(self): # set some values and leave out others self.config.LONG_VALUE = long(654321) self.config.BOOL_VALUE = False self.config.UNICODE_VALUE = six.u('Québec') self.config.DECIMAL_VALUE = Decimal('1.2') self.config.DATETIME_VALUE = datetime(1977, 10, 2) self.config.DATE_VALUE = date(2001, 12, 20) self.config.TIME_VALUE = time(1, 59, 0) self.assertEqual(self.config.INT_VALUE, 1) # this should be the default value self.assertEqual(self.config.LONG_VALUE, long(654321)) self.assertEqual(self.config.BOOL_VALUE, False) self.assertEqual(self.config.STRING_VALUE, 'Hello world') # this should be the default value self.assertEqual(self.config.UNICODE_VALUE, six.u('Québec')) self.assertEqual(self.config.DECIMAL_VALUE, Decimal('1.2')) self.assertEqual(self.config.DATETIME_VALUE, datetime(1977, 10, 2)) self.assertEqual(self.config.FLOAT_VALUE, 3.1415926536) # this should be the default value self.assertEqual(self.config.DATE_VALUE, date(2001, 12, 20)) self.assertEqual(self.config.TIME_VALUE, time(1, 59, 0))
def test_store(self): self.assertEqual(self.config.INT_VALUE, 1) self.assertEqual(self.config.LONG_VALUE, long(123456)) self.assertEqual(self.config.BOOL_VALUE, True) self.assertEqual(self.config.STRING_VALUE, "Hello world") self.assertEqual(self.config.UNICODE_VALUE, six.u("Rivière-Bonjour")) self.assertEqual(self.config.DECIMAL_VALUE, Decimal("0.1")) self.assertEqual(self.config.DATETIME_VALUE, datetime(2010, 8, 23, 11, 29, 24)) self.assertEqual(self.config.FLOAT_VALUE, 3.1415926536) self.assertEqual(self.config.DATE_VALUE, date(2010, 12, 24)) self.assertEqual(self.config.TIME_VALUE, time(23, 59, 59)) self.assertEqual(self.config.CHOICE_VALUE, "yes") self.assertEqual(self.config.EMAIL_VALUE, "*****@*****.**") # set values self.config.INT_VALUE = 100 self.config.LONG_VALUE = long(654321) self.config.BOOL_VALUE = False self.config.STRING_VALUE = "Beware the weeping angel" self.config.UNICODE_VALUE = six.u("Québec") self.config.DECIMAL_VALUE = Decimal("1.2") self.config.DATETIME_VALUE = datetime(1977, 10, 2) self.config.FLOAT_VALUE = 2.718281845905 self.config.DATE_VALUE = date(2001, 12, 20) self.config.TIME_VALUE = time(1, 59, 0) self.config.CHOICE_VALUE = "no" self.config.EMAIL_VALUE = "*****@*****.**" # read again self.assertEqual(self.config.INT_VALUE, 100) self.assertEqual(self.config.LONG_VALUE, long(654321)) self.assertEqual(self.config.BOOL_VALUE, False) self.assertEqual(self.config.STRING_VALUE, "Beware the weeping angel") self.assertEqual(self.config.UNICODE_VALUE, six.u("Québec")) self.assertEqual(self.config.DECIMAL_VALUE, Decimal("1.2")) self.assertEqual(self.config.DATETIME_VALUE, datetime(1977, 10, 2)) self.assertEqual(self.config.FLOAT_VALUE, 2.718281845905) self.assertEqual(self.config.DATE_VALUE, date(2001, 12, 20)) self.assertEqual(self.config.TIME_VALUE, time(1, 59, 0)) self.assertEqual(self.config.CHOICE_VALUE, "no") self.assertEqual(self.config.EMAIL_VALUE, "*****@*****.**")
def query2str(items): """Turns a dictionary into an easy-to-read list of key-value pairs. If there's a field called "password" it will be excluded from the output. """ kvs = [] for k, v in items: if k != 'password': kvs.append(six.u('%s=%s') % (k, v)) return '\n'.join(kvs)
def ensure_unicoded_and_unique(args_list): """ Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order. """ unicoded_args = [] for argument in args_list: argument = (six.u(argument) if not isinstance(argument, six.text_type) else argument) if argument not in unicoded_args: unicoded_args.append(argument) return unicoded_args
def cast(self, value): """ Returns a native Python object of the expected format. Will throw an exception if the value doesn't complies with any constraints. See for details: https://github.com/frictionlessdata/jsontableschema-py#types This method is mainly a helper for the validation_error :param value: :return: """ if isinstance(value, six.string_types) and not isinstance(value, six.text_type): # the StringType accepts only unicode value = six.u(value) return self.type.cast(value)
def query2str(items): """Turns a dictionary into an easy-to-read list of key-value pairs. If there's a field called "password" it will be excluded from the output. """ # Limit the length of the value to avoid a DoS attack value_maxlimit = 256 kvs = [] for k, v in items: if k != 'password': kvs.append(six.u('%s=%s') % (k, v[:256])) return '\n'.join(kvs)
def query2str(items, max_length=1024): """Turns a dictionary into an easy-to-read list of key-value pairs. If there's a field called "password" it will be excluded from the output. The length of the output is limited to max_length to avoid a DoS attack. """ kvs = [] for k, v in items: if k != PASSWORD_FORM_FIELD: kvs.append(six.u('%s=%s') % (k, v)) return '\n'.join(kvs)[:max_length]
def __init__(self, *args, **kwargs): kwargs.setdefault('blank', True) kwargs.setdefault('editable', False) populate_from = kwargs.pop('populate_from', None) if populate_from is None: raise ValueError("missing 'populate_from' argument") else: self._populate_from = populate_from self.separator = kwargs.pop('separator', six.u('-')) self.overwrite = kwargs.pop('overwrite', False) self.uppercase = kwargs.pop('uppercase', False) self.allow_duplicates = kwargs.pop('allow_duplicates', False) super(AutoSlugField, self).__init__(*args, **kwargs)
def __unicode__(self): """ String version of this object is the html output of head elements. """ if self.__cache_prefix is not None: value = cache.get(self.__cache_prefix) else: value = None if value is None: value = u'\n'.join(six.u(getattr(self, f)) for f, e in self.__metadata._meta.elements.items() if e.head) value = mark_safe(value) if self.__cache_prefix is not None: cache.set(self.__cache_prefix, value or '') return value
def render(self, context): try: target = self.target.resolve(context) except VariableDoesNotExist: msg = (u"{% get_metadata %} needs some path information.\n" u"Please use RequestContext with the django.core.context_processors.request context processor.\n" "Or provide a path or object explicitly, eg {% get_metadata for path %} or {% get_metadata for object %}") raise template.TemplateSyntaxError(msg) else: if callable(target): target = target() if isinstance(target, six.string_types): path = target elif hasattr(target, 'get_absolute_url'): path = target.get_absolute_url() elif hasattr(target, "__iter__") and 'get_absolute_url' in target: path = target['get_absolute_url']() else: path = None kwargs = {} # If a site is given, pass that on if self.site: kwargs['site'] = self.site.resolve(context) # If a language is given, pass that on if self.language: kwargs['language'] = self.language.resolve(context) metadata = None # If the target is a django model object if hasattr(target, 'pk'): metadata = get_linked_metadata(target, self.metadata_name, context, **kwargs) if not isinstance(path, six.string_types): path = None if not metadata: # Fetch the metadata try: metadata = get_metadata(path, self.metadata_name, context, **kwargs) except Exception as e: raise template.TemplateSyntaxError(e) # If a variable name is given, store the result there if self.variable_name is not None: context.dicts[0][self.variable_name] = metadata return "" else: return six.u(metadata)
def __getattr__(self, name): # If caching is enabled, work out a key if self.__cache_prefix: cache_key = '%s.%s' % (self.__cache_prefix, name) value = cache.get(cache_key) else: cache_key = None value = None # Look for a group called "name" if name in self.__metadata._meta.groups: if value is not None: value = mark_safe(value) return value or None value_list = [] for f in self.__metadata._meta.groups[name]: try: v = six.u(BoundMetadataField(self.__metadata._meta.elements[f], self._resolve_value(f))) except NameError: v = str(BoundMetadataField(self.__metadata._meta.elements[f], self._resolve_value(f))) value_list.append(v) value = '\n'.join(value_list).strip() if value is not None: value = mark_safe(value) # Look for an element called "name" elif name in self.__metadata._meta.elements: if value is not None: value = mark_safe(value) return BoundMetadataField(self.__metadata._meta.elements[name], value or None) value = self._resolve_value(name) if cache_key is not None: cache.set(cache_key, value or '') if value is not None: value = mark_safe(value) return BoundMetadataField(self.__metadata._meta.elements[name], value) else: raise AttributeError if cache_key is not None: cache.set(cache_key, value or '') if value is not None: value = mark_safe(value) return value or None
def test_missing_values(self): # set some values and leave out others self.config.LONG_VALUE = long(654321) self.config.BOOL_VALUE = False self.config.UNICODE_VALUE = six.u('Québec') self.config.DECIMAL_VALUE = Decimal('1.2') self.config.DATETIME_VALUE = datetime(1977, 10, 2) self.config.DATE_VALUE = date(2001, 12, 20) self.config.TIME_VALUE = time(1, 59, 0) self.assertEqual(self.config.INT_VALUE, 1) # this should be the default value self.assertEqual(self.config.LONG_VALUE, long(654321)) self.assertEqual(self.config.BOOL_VALUE, False) self.assertEqual(self.config.STRING_VALUE, 'Hello world') # this should be the default value self.assertEqual(self.config.UNICODE_VALUE, six.u('Québec')) self.assertEqual(self.config.DECIMAL_VALUE, Decimal('1.2')) self.assertEqual(self.config.DATETIME_VALUE, datetime(1977, 10, 2)) self.assertEqual(self.config.FLOAT_VALUE, 3.1415926536) # this should be the default value self.assertEqual(self.config.DATE_VALUE, date(2001, 12, 20)) self.assertEqual(self.config.TIME_VALUE, time(1, 59, 0)) self.assertEqual(self.config.CHOICE_VALUE, 'choice_1')
def get_value(obj, attr): """ Returns the value of an attribute. First it tries to return the unicode value. """ if hasattr(obj, attr): try: return getattr(obj, attr).__unicode__() except: value = getattr(obj, attr) if hasattr(value, 'all'): return [u(v) for v in value.all()] else: return value else: return None
def get_context(self): context = super(ChangePasswordView, self).get_context() helper = FormHelper() helper.form_tag = False self.form.helper = helper context.update({ 'title': _('Change password: %s') % escape(six.u(self.obj)), 'form': self.form, 'has_delete_permission': False, 'has_change_permission': True, 'has_view_permission': True, 'original': self.obj, }) return context
def cast(self, value): """ Returns a native Python object of the expected format. Will throw an exception if the value doesn't complies with any constraints. See for details: https://github.com/frictionlessdata/jsontableschema-py#types This method is mainly a helper for the validation_error :param value: :return: """ if isinstance(value, six.string_types) and not isinstance( value, six.text_type): # the StringType accepts only unicode value = six.u(value) elif isinstance(value, six.integer_types): value = '{}'.format(value) return self.type.cast(value)
def row_it(self, cast=True): for record in self.records: row = [] for field in self.schema.fields: value = record.data.get(field.name, '') if cast: # Cast to native python type try: value = field.cast(value) except Exception: pass # TODO: remove that when running in Python3 if isinstance(value, six.string_types) and not isinstance(value, six.text_type): value = six.u(value) row.append(value) yield row
def clone(self, forced_version_date=None): """ Clones a Versionable and returns a fresh copy of the original object. Original source: ClonableMixin snippet (http://djangosnippets.org/snippets/1271), with the pk/id change suggested in the comments :param forced_version_date: a timestamp including tzinfo; this value is usually set only internally! :return: returns a fresh clone of the original object (with adjusted relations) """ if not self.pk: raise ValueError('Instance must be saved before it can be cloned') if self.version_end_date: raise ValueError('This is a historical item and can not be cloned.') if forced_version_date: if not self.version_start_date <= forced_version_date <= get_utc_now(): raise ValueError('The clone date must be between the version start date and now.') else: forced_version_date = get_utc_now() earlier_version = self later_version = copy.copy(earlier_version) later_version.version_end_date = None later_version.version_start_date = forced_version_date # set earlier_version's ID to a new UUID so the clone (later_version) can # get the old one -- this allows 'head' to always have the original # id allowing us to get at all historic foreign key relationships earlier_version.id = six.u(str(uuid.uuid4())) earlier_version.version_end_date = forced_version_date earlier_version.save(create_new_version=False) later_version.save(create_new_version=False) # re-create ManyToMany relations for field in earlier_version._meta.many_to_many: earlier_version.clone_relations(later_version, field.attname) if hasattr(earlier_version._meta, 'many_to_many_related'): for rel in earlier_version._meta.many_to_many_related: earlier_version.clone_relations(later_version, rel.via_field_name) later_version.save(create_new_version=False) return later_version
def test_get_with_filter_unicode_no_match(self): with self.assertNumQueries(1): response = self.client.get( '/users/?filter{name}[]=%s' % UNICODE_URL_STRING ) self.assertEquals(200, response.status_code) self.assertEquals( {'users': []}, json.loads(response.content.decode('utf-8'))) with self.assertNumQueries(1): response = self.client.get( six.u('/users/?filter{name}[]=%s') % UNICODE_STRING ) self.assertEquals(200, response.status_code) self.assertEquals( {'users': []}, json.loads(response.content.decode('utf-8')))
def test_ng_length(self): first_name = self.dom("input[name=first_name]") self.assertEqual(len(first_name), 1) attrib = dict(first_name[0].attrib.items()) self.assertDictContainsSubset({"ng-required": "true"}, attrib) self.assertDictContainsSubset({"ng-minlength": "3"}, attrib) self.assertDictContainsSubset({"ng-maxlength": "20"}, attrib) lis = self.dom("label[for=id_first_name]").closest("th").next("td").children("ul.djng-field-errors > li") if VERSION[1] == 5: # Django < 1.6 not not know about minlength and maxlength self.assertEqual(len(lis), 2) else: self.assertEqual(len(lis), 4) attrib = dict(lis[0].attrib.items()) self.assertDictContainsSubset({"ng-show": self.form_name + "['first_name'].$error.required"}, attrib) attrib = dict(lis[1].attrib.items()) self.assertDictContainsSubset({"ng-show": self.form_name + six.u("['first_name'].$error.minlength")}, attrib)
def _create_at(self, timestamp=None, **kwargs): """ WARNING: Only for internal use and testing. Create a Versionable having a version_start_date and version_birth_date set to some pre-defined timestamp :param timestamp: point in time at which the instance has to be created :param kwargs: arguments needed for initializing the instance :return: an instance of the class """ ident = six.u(str(uuid.uuid4())) if timestamp is None: timestamp = get_utc_now() kwargs['id'] = ident kwargs['identity'] = ident kwargs['version_start_date'] = timestamp kwargs['version_birth_date'] = timestamp return super(VersionManager, self).create(**kwargs)
def test_ng_length(self): first_name = self.dom('input[name=first_name]') self.assertEqual(len(first_name), 1) attrib = dict(first_name[0].attrib.items()) self.assertDictContainsSubset({'ng-required': 'true'}, attrib) self.assertDictContainsSubset({'ng-minlength': '3'}, attrib) self.assertDictContainsSubset({'ng-maxlength': '20'}, attrib) lis = self.dom('label[for=id_first_name]').closest('th').next('td').children('ul.djng-field-errors > li') if VERSION[1] == 5: # Django < 1.6 not not know about minlength and maxlength self.assertEqual(len(lis), 2) else: self.assertEqual(len(lis), 4) attrib = dict(lis[0].attrib.items()) self.assertDictContainsSubset({'ng-show': self.form_name + '[\'first_name\'].$error.required'}, attrib) attrib = dict(lis[1].attrib.items()) self.assertDictContainsSubset({'ng-show': self.form_name + six.u('[\'first_name\'].$error.minlength')}, attrib)
def uuid(uuid_value=None): """ Returns a uuid value that is valid to use for id and identity fields. :return: unicode uuid object if using UUIDFields, uuid unicode string otherwise. """ if uuid_value: if not validate_uuid(uuid_value): raise ValueError( "uuid_value must be a valid UUID version 4 object") else: uuid_value = uuid.uuid4() if versions_settings.VERSIONS_USE_UUIDFIELD: return uuid_value else: return six.u(str(uuid_value))
def __init__(self, *args, **kwargs): kwargs.setdefault('blank', True) kwargs.setdefault('editable', False) populate_from = kwargs.pop('populate_from', None) if populate_from is None: raise ValueError("missing 'populate_from' argument") else: self._populate_from = populate_from self.separator = kwargs.pop('separator', six.u('-')) self.overwrite = kwargs.pop('overwrite', False) self.uppercase = kwargs.pop('uppercase', False) self.allow_duplicates = kwargs.pop('allow_duplicates', False) # not override parameter if it was passed explicitly, # so passed parameters takes precedence over the setting if settings.OSCAR_SLUG_ALLOW_UNICODE: kwargs.setdefault('allow_unicode', settings.OSCAR_SLUG_ALLOW_UNICODE) super(AutoSlugField, self).__init__(*args, **kwargs)
def render(self, name, value=None, attrs=None): final_attrs = self.build_attrs(attrs, name=name) code_set_value = '' if value: code_set_value = ('''entityChoiceField_set(%(id)s, %(value)s);''' % { 'id': json.dumps(final_attrs['id']), 'value': json.dumps(str(value)) }) return mark_safe( six.u('''<input type='hidden' id=%(id)s name=%(name)s /> <script type='text/javascript'>//<!-- $(function(){ create_entityChoiceField(%(id)s, %(params)s); %(code_set_value)s });//--></script>''') % { 'name': json.dumps(name), 'id': json.dumps(final_attrs['id']), 'params': json.dumps({'type': self.type}), 'code_set_value': code_set_value })
def cast(self, value): """ Returns o native Python object of the expected format. Will throw an exception if the value doesn't complies with any constraints. This method delegates most of the cast to the tableschema.Field.cast_value. Except for - date and dateTime with format='any'. This because the tableschema.Field.cast_value interprets an ambiguous day/month/year date as month/day/year (american way) :param value: :return: """ # we want to strip strings if isinstance(value, six.string_types): value = value.strip() # TODO: remove that when running in Python3 if not isinstance(value, six.text_type): # the ensure only unicode value = six.u(value).strip() # date or datetime with format='any if self.is_datetime_types and self.format == 'any' and value: return cast_date_any_format( value) if self.is_date_type else cast_datetime_any_format( value) # delegates to tableschema.Field.cast_value return self.tableschema_field.cast_value(value, constraints=True)
def __unicode__(self): """For the admin.""" return six.u('Attempted Access: %s') % self.attempt_time
def __str__(self): result = six.u('Success') if self else six.u('Failure') email = getattr(self, 'email', None) email_string = six.u(' email={0}').format(email) if email else six.u('') return six.u('<VerificationResult {0}{1}>').format(result, email_string)
def __unicode__(self): return six.u('Access Log for %s @ %s') % (self.username, self.attempt_time)
def __unicode__(self): return six.u('Attempted Access: %s') % self.attempt_time
def test_invalid_assertion(): form = BrowserIDForm({'assertion': six.u('\xe3')}) assert not form.is_valid()
def __str__(self): return six.u('%s (%s)') % (self.humanName, self.owner)
def __unicode__(self): return _(six.u('Group Avatar for %s')) % self.group
class CustomSluggedTestModel(models.Model): title = models.CharField(max_length=42) slug = AutoSlugField(populate_from='title', separator=six.u("_"), uppercase=True)
def test_unicode_and_bytestring_kwargs(self): self.assertEqual(self.job.key(spam=six.b('eggs')), self.job.key(spam=six.u('eggs')))
def test_str_unicode(self): # Ensure that __str__ can handle unicode values. result = base.VerificationResult({'status': 'okay', 'email': six.u('\[email protected]')}) eq_(six.text_type(result), six.u('<VerificationResult Success email=\[email protected]>'))
def get_pagination_context(page, pages_to_show=11, url=None, size=None, extra=None): """ Generate Bootstrap pagination context from a page object """ pages_to_show = int(pages_to_show) if pages_to_show < 1: raise ValueError("Pagination pages_to_show should be a positive " + "integer, you specified {pages}".format(pages=pages_to_show)) num_pages = page.paginator.num_pages current_page = page.number half_page_num = int(floor(pages_to_show / 2)) - 1 if half_page_num < 0: half_page_num = 0 first_page = current_page - half_page_num if first_page <= 1: first_page = 1 if first_page > 1: pages_back = first_page - half_page_num if pages_back < 1: pages_back = 1 else: pages_back = None last_page = first_page + pages_to_show - 1 if pages_back is None: last_page += 1 if last_page > num_pages: last_page = num_pages if last_page < num_pages: pages_forward = last_page + half_page_num if pages_forward > num_pages: pages_forward = num_pages else: pages_forward = None if first_page > 1: first_page -= 1 if pages_back is not None and pages_back > 1: pages_back -= 1 else: pages_back = None pages_shown = [] for i in range(first_page, last_page + 1): pages_shown.append(i) # Append proper character to url if url: # Remove existing page GET parameters url = six.u(url) url = re.sub(r'\?page\=[^\&]+', '?', url) url = re.sub(r'\&page\=[^\&]+', '', url) # Append proper separator if '?' in url: url += '&' else: url += '?' # Append extra string to url if extra: if not url: url = '?' url += six.u(extra) + '&' if url: url = url.replace('?&', '?') # Set CSS classes,see twitter.github.io/bootstrap/components.html#pagination pagination_css_classes = ['pagination'] if size == 'small': pagination_css_classes.append('pagination-sm') elif size == 'large': pagination_css_classes.append('pagination-lg') # Build context object return { 'bootstrap_pagination_url': url, 'num_pages': num_pages, 'current_page': current_page, 'first_page': first_page, 'last_page': last_page, 'pages_shown': pages_shown, 'pages_back': pages_back, 'pages_forward': pages_forward, 'pagination_css_classes': ' '.join(pagination_css_classes), }
def __str__(self): return _(six.u('Avatar for %s')) % self.user
def __str__(self): return six.u("<Subscription(%s for %s)>") % (self.user.humanName, self.event.humanName)
class AbstractCommunicationEventType(models.Model): """ A 'type' of communication. Like an order confirmation email. """ #: Code used for looking up this event programmatically. # e.g. PASSWORD_RESET. AutoSlugField uppercases the code for us because # it's a useful convention that's been enforced in previous Oscar versions code = AutoSlugField( _('Code'), max_length=128, unique=True, populate_from='name', separator=six.u("_"), uppercase=True, editable=True, validators=[ RegexValidator( regex=r'^[a-zA-Z_][0-9a-zA-Z_]*$', message=_( "Code can only contain the letters a-z, A-Z, digits, " "and underscores, and can't start with a digit."))], help_text=_("Code used for looking up this event programmatically")) #: Name is the friendly description of an event for use in the admin name = models.CharField( _('Name'), max_length=255, help_text=_("This is just used for organisational purposes")) # We allow communication types to be categorised # For backwards-compatibility, the choice values are quite verbose ORDER_RELATED = 'Order related' USER_RELATED = 'User related' CATEGORY_CHOICES = ( (ORDER_RELATED, _('Order related')), (USER_RELATED, _('User related')) ) category = models.CharField( _('Category'), max_length=255, default=ORDER_RELATED, choices=CATEGORY_CHOICES) # Template content for emails # NOTE: There's an intentional distinction between None and ''. None # instructs Oscar to look for a file-based template, '' is just an empty # template. email_subject_template = models.CharField( _('Email Subject Template'), max_length=255, blank=True, null=True) email_body_template = models.TextField( _('Email Body Template'), blank=True, null=True) email_body_html_template = models.TextField( _('Email Body HTML Template'), blank=True, null=True, help_text=_("HTML template")) # Template content for SMS messages sms_template = models.CharField(_('SMS Template'), max_length=170, blank=True, null=True, help_text=_("SMS template")) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) date_updated = models.DateTimeField(_("Date Updated"), auto_now=True) objects = CommunicationTypeManager() # File templates email_subject_template_file = 'customer/emails/commtype_%s_subject.txt' email_body_template_file = 'customer/emails/commtype_%s_body.txt' email_body_html_template_file = 'customer/emails/commtype_%s_body.html' sms_template_file = 'customer/sms/commtype_%s_body.txt' class Meta: abstract = True app_label = 'customer' verbose_name = _("Communication event type") verbose_name_plural = _("Communication event types") def get_messages(self, ctx=None): """ Return a dict of templates with the context merged in We look first at the field templates but fail over to a set of file templates that follow a conventional path. """ code = self.code.lower() # Build a dict of message name to Template instances templates = {'subject': 'email_subject_template', 'body': 'email_body_template', 'html': 'email_body_html_template', 'sms': 'sms_template'} for name, attr_name in templates.items(): field = getattr(self, attr_name, None) if field is not None: # Template content is in a model field templates[name] = Template(field) else: # Model field is empty - look for a file template template_name = getattr(self, "%s_file" % attr_name) % code try: templates[name] = get_template(template_name) except TemplateDoesNotExist: templates[name] = None # Pass base URL for serving images within HTML emails if ctx is None: ctx = {} ctx['static_base_url'] = getattr( settings, 'OSCAR_STATIC_BASE_URL', None) messages = {} for name, template in templates.items(): messages[name] = template.render(Context(ctx)) if template else '' # Ensure the email subject doesn't contain any newlines messages['subject'] = messages['subject'].replace("\n", "") messages['subject'] = messages['subject'].replace("\r", "") return messages def __str__(self): return self.name def is_order_related(self): return self.category == self.ORDER_RELATED def is_user_related(self): return self.category == self.USER_RELATED
def __str__(self): return u("%s") % self.robot
def __unicode__(self): return _(six.u('%s avatar for %s')) % ("Main" if self.social is None else self.social, self.user)
def __str__(self): return u("%s") % self.pattern
def __unicode__(self): return _(six.u('Avatar for %s')) % self.user
ROOT_URLCONF = 'tests.urls' CONSTANCE_REDIS_CONNECTION_CLASS = 'tests.redis_mockup.Connection' long_value = 123456 if not six.PY3: long_value = long(long_value) CONSTANCE_CONFIG = { 'INT_VALUE': (1, 'some int'), 'LONG_VALUE': (long_value, 'some looong int'), 'BOOL_VALUE': (True, 'true or false'), 'STRING_VALUE': ('Hello world', 'greetings'), 'UNICODE_VALUE': (six.u('Rivière-Bonjour'), 'greetings'), 'DECIMAL_VALUE': (Decimal('0.1'), 'the first release version'), 'DATETIME_VALUE': (datetime(2010, 8, 23, 11, 29, 24), 'time of the first commit'), 'FLOAT_VALUE': (3.1415926536, 'PI'), 'DATE_VALUE': (date(2010, 12, 24), 'Merry Chrismas'), 'TIME_VALUE': (time(23, 59, 59), 'And happy New Year'), 'LINEBREAK_VALUE': ('Spam spam', 'eggs\neggs'), } DEBUG = True STATIC_ROOT = './static/' STATIC_URL = '/static/'