Here are the examples of the python api django.utils.six.text_type taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
415 Examples
3
Source : filters.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def filter(self, qs, value):
if isinstance(value, Lookup):
lookup = six.text_type(value.lookup_type)
value = value.value
else:
lookup = self.lookup_expr
if value in EMPTY_VALUES:
return qs
if self.distinct:
qs = qs.distinct()
qs = self.get_method(qs)(**{'%s__%s' % (self.field_name, lookup): value})
return qs
class CharFilter(Filter):
3
Source : backends.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def get_coreschema_field(self, field):
if isinstance(field, filters.NumberFilter):
field_cls = compat.coreschema.Number
else:
field_cls = compat.coreschema.String
return field_cls(
description=six.text_type(field.extra.get('help_text', ''))
)
def get_schema_fields(self, view):
3
Source : exceptions.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def __repr__(self):
return unicode_to_repr('ErrorDetail(string=%r, code=%r)' % (
six.text_type(self),
self.code,
))
class APIException(Exception):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def run_validation(self, data=empty):
# Test for the empty string here so that it does not get validated,
# and so that subclasses do not need to handle it explicitly
# inside the `to_internal_value()` method.
if data == '' or (self.trim_whitespace and six.text_type(data).strip() == ''):
if not self.allow_blank:
self.fail('blank')
return ''
return super(CharField, self).run_validation(data)
def to_internal_value(self, data):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def __init__(self, **kwargs):
self.max_value = kwargs.pop('max_value', None)
self.min_value = kwargs.pop('min_value', None)
super(IntegerField, self).__init__(**kwargs)
if self.max_value is not None:
message = lazy(
self.error_messages['max_value'].format,
six.text_type)(max_value=self.max_value)
self.validators.append(
MaxValueValidator(self.max_value, message=message))
if self.min_value is not None:
message = lazy(
self.error_messages['min_value'].format,
six.text_type)(min_value=self.min_value)
self.validators.append(
MinValueValidator(self.min_value, message=message))
def to_internal_value(self, data):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_internal_value(self, data):
if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')
try:
data = int(self.re_decimal.sub('', str(data)))
except (ValueError, TypeError):
self.fail('invalid')
return data
def to_representation(self, value):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def __init__(self, **kwargs):
self.max_value = kwargs.pop('max_value', None)
self.min_value = kwargs.pop('min_value', None)
super(FloatField, self).__init__(**kwargs)
if self.max_value is not None:
message = lazy(
self.error_messages['max_value'].format,
six.text_type)(max_value=self.max_value)
self.validators.append(
MaxValueValidator(self.max_value, message=message))
if self.min_value is not None:
message = lazy(
self.error_messages['min_value'].format,
six.text_type)(min_value=self.min_value)
self.validators.append(
MinValueValidator(self.min_value, message=message))
def to_internal_value(self, data):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_internal_value(self, data):
if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')
try:
return float(data)
except (TypeError, ValueError):
self.fail('invalid')
def to_representation(self, value):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_representation(self, value):
coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING)
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(six.text_type(value).strip())
quantized = self.quantize(value)
if not coerce_to_string:
return quantized
if self.localize:
return localize_input(quantized)
return '{0:f}'.format(quantized)
def quantize(self, value):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_internal_value(self, value):
if isinstance(value, datetime.timedelta):
return value
parsed = parse_duration(six.text_type(value))
if parsed is not None:
return parsed
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
def to_representation(self, value):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_internal_value(self, data):
if data == '' and self.allow_blank:
return ''
try:
return self.choice_strings_to_values[six.text_type(data)]
except KeyError:
self.fail('invalid_choice', input=data)
def to_representation(self, value):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_representation(self, value):
if value in ('', None):
return value
return self.choice_strings_to_values.get(six.text_type(value), value)
def iter_options(self):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def _set_choices(self, choices):
self.grouped_choices = to_choices_dict(choices)
self._choices = flatten_choices_dict(self.grouped_choices)
# Map the string representation of choices to the underlying value.
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = {
six.text_type(key): key for key in self.choices
}
choices = property(_get_choices, _set_choices)
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_representation(self, value):
return {
self.choice_strings_to_values.get(six.text_type(item), item) for item in value
}
class FilePathField(ChoiceField):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_representation(self, value):
"""
List of object instances -> List of dicts of primitive datatypes.
"""
return {
six.text_type(key): self.child.to_representation(val) if val is not None else None
for key, val in value.items()
}
def run_child_validation(self, data):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def run_child_validation(self, data):
result = {}
errors = OrderedDict()
for key, value in data.items():
key = six.text_type(key)
try:
result[key] = self.child.run_validation(value)
except ValidationError as e:
errors[key] = e.detail
if not errors:
return result
raise ValidationError(errors)
class HStoreField(DictField):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def get_value(self, dictionary):
if html.is_html_input(dictionary) and self.field_name in dictionary:
# When HTML form input is used, mark up the input
# as being a JSON string, rather than a JSON primitive.
class JSONString(six.text_type):
def __new__(self, value):
ret = six.text_type.__new__(self, value)
ret.is_json_string = True
return ret
return JSONString(dictionary[self.field_name])
return dictionary.get(self.field_name, empty)
def to_internal_value(self, data):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def to_representation(self, value):
if self.binary:
value = json.dumps(value)
# On python 2.x the return type for json.dumps() is underspecified.
# On python 3.x json.dumps() returns unicode strings.
if isinstance(value, six.text_type):
value = bytes(value.encode('utf-8'))
return value
# Miscellaneous field types...
class ReadOnlyField(Field):
3
Source : fields.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def __init__(self, model_field, **kwargs):
self.model_field = model_field
# The `max_length` option is supported by Django's base `Field` class,
# so we'd better support it here.
max_length = kwargs.pop('max_length', None)
super(ModelField, self).__init__(**kwargs)
if max_length is not None:
message = lazy(
self.error_messages['max_length'].format,
six.text_type)(max_length=self.max_length)
self.validators.append(
MaxLengthValidator(self.max_length, message=message))
def to_internal_value(self, data):
3
Source : pagination.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def _get_position_from_instance(self, instance, ordering):
field_name = ordering[0].lstrip('-')
if isinstance(instance, dict):
attr = instance[field_name]
else:
attr = getattr(instance, field_name)
return six.text_type(attr)
def get_paginated_response(self, data):
3
Source : parsers.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as JSON and returns the resulting data.
"""
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
try:
decoded_stream = codecs.getreader(encoding)(stream)
parse_constant = json.strict_constant if self.strict else None
return json.load(decoded_stream, parse_constant=parse_constant)
except ValueError as exc:
raise ParseError('JSON parse error - %s' % six.text_type(exc))
class FormParser(BaseParser):
3
Source : relations.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def name(self):
# This ensures that we only called `__str__` lazily,
# as in some cases calling __str__ on a model instances *might*
# involve a database lookup.
return six.text_type(self.obj)
is_hyperlink = True
3
Source : helpers.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def __init__(self, form, field, readonly_fields=None, model_admin=None):
self.form = form # A django.forms.Form instance
if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
self.fields = [field]
else:
self.fields = field
self.has_visible_field = not all(
field in self.form.fields and self.form.fields[field].widget.is_hidden
for field in self.fields
)
self.model_admin = model_admin
if readonly_fields is None:
readonly_fields = ()
self.readonly_fields = readonly_fields
def __iter__(self):
3
Source : models.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def __str__(self):
return "%s | %s | %s" % (
six.text_type(self.content_type.app_label),
six.text_type(self.content_type),
six.text_type(self.name))
def natural_key(self):
3
Source : tokens.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def _make_hash_value(self, user, timestamp):
# Ensure results are consistent across DB backends
login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)
return (
six.text_type(user.pk) + user.password +
six.text_type(login_timestamp) + six.text_type(timestamp)
)
def _num_days(self, dt):
3
Source : array.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def prepare_value(self, value):
if isinstance(value, list):
return self.delimiter.join(six.text_type(self.base_field.prepare_value(v)) for v in value)
return value
def to_python(self, value):
3
Source : base.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def endswith_cr(line):
"""
Return True if line (a text or byte string) ends with '\r'.
"""
return line.endswith('\r' if isinstance(line, six.text_type) else b'\r')
def endswith_lf(line):
3
Source : base.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def endswith_lf(line):
"""
Return True if line (a text or byte string) ends with '\n'.
"""
return line.endswith('\n' if isinstance(line, six.text_type) else b'\n')
def equals_lf(line):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def adapt_datefield_value(self, value):
"""
Transforms a date value to an object compatible with what is expected
by the backend driver for date columns.
"""
if value is None:
return None
return six.text_type(value)
def adapt_datetimefield_value(self, value):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def adapt_datetimefield_value(self, value):
"""
Transforms a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
return six.text_type(value)
def adapt_timefield_value(self, value):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def adapt_timefield_value(self, value):
"""
Transforms a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
if timezone.is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
return six.text_type(value)
def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
3
Source : base.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_new_connection(self, conn_params):
conn = Database.connect(**conn_params)
conn.encoders[SafeText] = conn.encoders[six.text_type]
conn.encoders[SafeBytes] = conn.encoders[bytes]
return conn
def init_connection_state(self):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def adapt_timefield_value(self, value):
if value is None:
return None
# Expression values are adapted by the database.
if hasattr(value, 'resolve_expression'):
return value
# MySQL doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware times.")
return six.text_type(value)
def max_name_length(self):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def adapt_datetimefield_value(self, value):
if value is None:
return None
# Expression values are adapted by the database.
if hasattr(value, 'resolve_expression'):
return value
# SQLite doesn't support tz-aware datetimes
if timezone.is_aware(value):
if settings.USE_TZ:
value = timezone.make_naive(value, self.connection.timezone)
else:
raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
return six.text_type(value)
def adapt_timefield_value(self, value):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def adapt_timefield_value(self, value):
if value is None:
return None
# Expression values are adapted by the database.
if hasattr(value, 'resolve_expression'):
return value
# SQLite doesn't support tz-aware datetimes
if timezone.is_aware(value):
raise ValueError("SQLite backend does not support timezone-aware times.")
return six.text_type(value)
def get_db_converters(self, expression):
3
Source : base.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def __repr__(self):
try:
u = six.text_type(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return force_str(' < %s: %s>' % (self.__class__.__name__, u))
def __str__(self):
3
Source : base.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages['unique_for_date'],
code='unique_for_date',
params={
'model': self,
'model_name': six.text_type(capfirst(opts.verbose_name)),
'lookup_type': lookup_type,
'field': field_name,
'field_label': six.text_type(capfirst(field.verbose_name)),
'date_field': unique_for,
'date_field_label': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
}
)
def unique_error_message(self, model_class, unique_check):
3
Source : files.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_prep_value(self, value):
"Returns field's value prepared for saving into a database."
value = super(FileField, self).get_prep_value(value)
# Need to convert File objects provided via a form to unicode for database insertion
if value is None:
return None
return six.text_type(value)
def pre_save(self, model_instance, add):
3
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def _get_default(self):
if self.has_default():
if callable(self.default):
return self.default
return lambda: self.default
if not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls:
return return_None
return six.text_type # returns empty string
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None):
3
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_prep_value(self, value):
value = super(FilePathField, self).get_prep_value(value)
if value is None:
return None
return six.text_type(value)
def formfield(self, **kwargs):
3
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_prep_value(self, value):
value = super(IPAddressField, self).get_prep_value(value)
if value is None:
return None
return six.text_type(value)
def get_internal_type(self):
3
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_prep_value(self, value):
value = super(GenericIPAddressField, self).get_prep_value(value)
if value is None:
return None
if value and ':' in value:
try:
return clean_ipv6_address(value, self.unpack_ipv4)
except exceptions.ValidationError:
pass
return six.text_type(value)
def formfield(self, **kwargs):
3
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def to_python(self, value):
# If it's a string, it should be base64-encoded data
if isinstance(value, six.text_type):
return six.memoryview(b64decode(force_bytes(value)))
return value
class UUIDField(Field):
3
Source : fields.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def to_python(self, value):
# Try to coerce the value to unicode.
unicode_value = force_text(value, strings_only=True)
if isinstance(unicode_value, six.text_type):
value = unicode_value.strip()
# If unicode, try to strptime against each input format.
if isinstance(value, six.text_type):
for format in self.input_formats:
try:
return self.strptime(value, format)
except (ValueError, TypeError):
continue
raise ValidationError(self.error_messages['invalid'], code='invalid')
def strptime(self, value, format):
3
Source : formsets.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def as_table(self):
"Returns this formset rendered as HTML < tr>s -- excluding the < table> < /table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = ' '.join(form.as_table() for form in self)
return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
def as_p(self):
3
Source : formsets.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def as_p(self):
"Returns this formset rendered as HTML < p>s."
forms = ' '.join(form.as_p() for form in self)
return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
def as_ul(self):
3
Source : formsets.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def as_ul(self):
"Returns this formset rendered as HTML < li>s."
forms = ' '.join(form.as_ul() for form in self)
return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
3
Source : models.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_unique_error_message(self, unique_check):
if len(unique_check) == 1:
return ugettext("Please correct the duplicate data for %(field)s.") % {
"field": unique_check[0],
}
else:
return ugettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
"field": get_text_list(unique_check, six.text_type(_("and"))),
}
def get_date_error_message(self, date_check):
3
Source : models.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get_date_error_message(self, date_check):
return ugettext(
"Please correct the duplicate data for %(field_name)s "
"which must be unique for the %(lookup)s in %(date_field)s."
) % {
'field_name': date_check[2],
'date_field': date_check[3],
'lookup': six.text_type(date_check[1]),
}
def get_form_error(self):
3
Source : models.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def prepare_value(self, value):
if (hasattr(value, '__iter__') and
not isinstance(value, six.text_type) and
not hasattr(value, '_meta')):
return [super(ModelMultipleChoiceField, self).prepare_value(v) for v in value]
return super(ModelMultipleChoiceField, self).prepare_value(value)
def has_changed(self, initial, data):
See More Examples