Here are the examples of the python api django.utils.encoding.smart_text taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
159 Examples
3
Example 1
def from_native(self, value):
if isinstance(value, six.string_types):
return value
if value is None:
return u''
return smart_text(value)
3
Example 2
Project: django-jet Source File: test_filters.py
def test_related_field_ajax_list_filter_with_initial(self):
initial = self.models[1]
request = self.factory.get('url', {'field__id__exact': initial.pk})
field, lookup_params, model, model_admin, field_path = self.get_related_field_ajax_list_filter_params()
list_filter = RelatedFieldAjaxListFilter(field, request, lookup_params, model, model_admin, field_path)
self.assertTrue(list_filter.has_output())
choices = list_filter.field_choices(field, request, model_admin)
self.assertIsInstance(choices, list)
self.assertEqual(len(choices), 1)
self.assertEqual(choices[0], (initial.pk, smart_text(initial)))
3
Example 3
def get_prep_value(self, value):
if value is None:
return value
elif _is_gettext_promise(value):
value = smart_text(value._proxy____args[0])
return smart_text(value)
3
Example 4
Project: 2buntu-blog Source File: fields.py
def validate(self, value):
super(CaptchaField, self).validate(value)
params = urlencode({
'secret': settings.RECAPTCHA_SECRET_KEY,
'response': smart_bytes(value),
'remoteip': self.get_remoteip(),
})
url = 'https://www.google.com/recaptcha/api/siteverify?%s' % params
if not loads(smart_text(urlopen(url).read())).get('success', False):
raise ValidationError("Incorrect captcha solution provided.")
return value
3
Example 5
def help_text_for_field(name, model):
help_text = ""
try:
field = _get_non_gfk_field(model._meta, name)
except (FieldDoesNotExist, FieldIsAForeignKeyColumnName):
pass
else:
if hasattr(field, 'help_text'):
help_text = field.help_text
return smart_text(help_text)
3
Example 6
def append(self, msg, msg_type='normal'):
new_message = FlashMessage(**{
'message': smart_text(msg, encoding="utf8"),
'kind': msg_type,
'is_error': msg_type == 'error'
})
new_hash = new_message.hash()
for message in self.messages:
if message.hash() == new_hash:
return
self.messages.append(new_message)
self.request.session[self.SESSION_KEY] = [m.json_ready() for m in self.messages]
3
Example 7
def choices(self, cl):
yield {
'selected': self.lookup_val is None,
'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
'display': _('All')
}
for pk, title in self.lookup_choices:
yield {
'selected': pk == int(self.lookup_val or '0'),
'query_string': cl.get_query_string({self.lookup_kwarg: pk}),
'display': mark_safe(smart_text(title))
}
3
Example 8
Project: tendenci Source File: pybb_tags.py
@register.simple_tag
def pybb_link(object, anchor=''):
"""
Return A tag with link to object.
"""
url = hasattr(object, 'get_absolute_url') and object.get_absolute_url() or None
#noinspection PyRedeclaration
anchor = anchor or smart_text(object)
return mark_safe('<a href="%s">%s</a>' % (url, escape(anchor)))
3
Example 9
def get_prep_value(self, value):
"""Overrides ``models.Field`` method. This is used to convert
the value from an instances of this class to bytes that can be
inserted into the database.
"""
if value is None:
return None
else:
return encoding.smart_text(base64.b64encode(pickle.dumps(value)))
3
Example 10
def to_internal_value(self, data):
try:
return self.get_queryset().get(**{self.slug_field: data})
except ObjectDoesNotExist:
self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data))
except (TypeError, ValueError):
self.fail('invalid')
3
Example 11
def get_for_model(self, model, for_concrete_model=True):
if for_concrete_model:
model = model._meta.concrete_model
elif model._deferred:
model = model._meta.proxy_for_model
opts = model._meta
try:
ct = self._get_from_cache(opts)
except KeyError:
ct, created = self.get_or_create(
app_label=opts.app_label,
model=opts.object_name.lower(),
defaults={'name': smart_text(opts.verbose_name_raw)},
)
self._add_to_cache(self.db, ct)
return ct
3
Example 12
def __call__(self, *args, **kwargs):
k = lambda o: o.cache_key if hasattr(o, 'cache_key') else o
arg_keys = list(map(k, args))
kwarg_keys = [(key, k(val)) for key, val in list(kwargs.items())]
key_parts = ('m', self.obj.cache_key, self.func.__name__,
arg_keys, kwarg_keys)
key = ':'.join(map(encoding.smart_text, key_parts))
if key not in self.cache:
f = functools.partial(self.func, self.obj, *args, **kwargs)
self.cache[key] = cached_with(self.obj, f, key)
return self.cache[key]
3
Example 13
def represent_data(self, data):
if isinstance(data, EmbeddedDocuement):
field = GenericEmbeddedField()
return field.to_representation(data)
elif isinstance(data, dict):
return dict([(key, self.represent_data(val)) for key, val in data.items()])
elif isinstance(data, list):
return [self.represent_data(value) for value in data]
elif data is None:
return None
else:
return smart_text(data, strings_only=True)
3
Example 14
Project: edx-ora2 Source File: filesystem.py
def make_upload_url_available(url_key_name, timeout):
"""
Authorize an upload URL.
Arguments:
url_key_name (str): key that uniquely identifies the upload url
timeout (int): time in seconds before the url expires
"""
get_cache().set(
smart_text(get_upload_cache_key(url_key_name)),
1, timeout
)
3
Example 15
def valid_value(self, value):
"""
Check to see if the provided value is a valid choice.
"""
for k, v in self.choices:
if isinstance(v, (list, tuple)):
# This is an optgroup, so look inside the group for options
for k2, v2 in v:
if value == smart_text(k2):
return True
else:
if value == smart_text(k) or value == k:
return True
return False
3
Example 16
Project: django-blog-zinnia Source File: test_feeds.py
def test_category_title_non_ascii(self):
self.create_published_entry()
self.category.title = smart_text('Catégorie')
self.category.save()
feed = CategoryEntries()
self.assertEqual(feed.get_title(self.category),
'Entries for the category %s' % self.category.title)
self.assertEqual(
feed.description(self.category),
'The last entries categorized under %s' % self.category.title)
3
Example 17
Project: cadasta-platform Source File: renderers.py
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement(self.element_node, {})
self._to_xml(xml, item)
xml.endElement(self.element_node)
elif isinstance(data, dict):
for key, value in six.iteritems(data):
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
# elif data is None:
# # Don't output any value
# pass
else:
xml.characters(smart_text(data))
3
Example 18
def render(self, request, **kwargs):
form_class = self.form.form()
prefix = 'fc%d' % self.id
formcontent = request.POST.get('_formcontent')
if request.method == 'POST' and (
not formcontent or formcontent == smart_text(self.id)):
form_instance = form_class(request.POST, prefix=prefix)
if form_instance.is_valid():
return self.process_valid_form(
request, form_instance, **kwargs)
else:
form_instance = form_class(prefix=prefix)
context = RequestContext(
request, {'content': self, 'form': form_instance})
return render_to_string(self.template, context)
3
Example 19
@register.simple_tag
def link(object, anchor=''):
"""
Return A tag with link to object.
"""
url = hasattr(object, 'get_absolute_url') and object.get_absolute_url() or None
anchor = anchor or smart_text(object)
return mark_safe('<a href="%s">%s</a>' % (url, escape(anchor)))
3
Example 20
def make_key(model, prefix, kwargs):
kwargs_bits = []
for k, v in sorted(six.iteritems(kwargs)):
k = __prep_key(model, k)
v = smart_text(__prep_value(model, k, v))
kwargs_bits.append('%s=%s' % (k, v))
kwargs_bits = ':'.join(kwargs_bits)
return '%s:%s:%s' % (
prefix,
model.__name__,
md5_text(kwargs_bits).hexdigest()
)
3
Example 21
def _get_dump_object(self, obj):
if isinstance(obj, TypedModel):
return {
"pk": smart_text(obj._get_pk_val(), strings_only=True),
"model": smart_text(getattr(obj, 'base_class', obj)._meta),
"fields": self._current
}
else:
return _python_serializer_get_dump_object(self, obj)
3
Example 22
def _start_object(self, obj):
if isinstance(obj, TypedModel):
self.indent(1)
obj_pk = obj._get_pk_val()
modelname = smart_text(getattr(obj, 'base_class', obj)._meta)
if obj_pk is None:
attrs = {"model": modelname,}
else:
attrs = {
"pk": smart_text(obj._get_pk_val()),
"model": modelname,
}
self.xml.startElement("object", attrs)
else:
return _xml_serializer_start_object(self, obj)
3
Example 23
Project: djangobb Source File: forum_extras.py
@register.simple_tag
def lofi_link(object, anchor=''):
"""
Return A tag with lofi_link to object.
"""
url = hasattr(object, 'get_absolute_url') and object.get_absolute_url() or None
anchor = anchor or smart_text(object)
return mark_safe('<a href="%slofi/">%s</a>' % (url, escape(anchor)))
3
Example 24
@classmethod
def _cache_key(cls, pk, db=None):
"""
Return a string that uniquely identifies the object.
For the Addon class, with a pk of 2, we get "o:addons.addon:2".
"""
if db:
key_parts = ('o', cls._meta, pk, db)
else:
key_parts = ('o', cls._meta, pk)
return ':'.join(map(encoding.smart_text, key_parts))
3
Example 25
Project: django-rest-framework Source File: views.py
def get_view_description(view_cls, html=False):
"""
Given a view class, return a textual description to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
"""
description = view_cls.__doc__ or ''
description = formatting.dedent(smart_text(description))
if html:
return formatting.markup_description(description)
return description
3
Example 26
def value_to_string(self, obj):
val = self._get_val_from_obj(obj)
if val is None:
data = ''
else:
data = smart_text(val)
return data
3
Example 27
def __str__(self):
return self.label or smart_text(
'%s<pk=%s, parent=%s<pk=%s, %s>, region=%s,'
' ordering=%d>') % (
self.__class__.__name__,
self.pk,
self.parent.__class__.__name__,
self.parent.pk,
self.parent,
self.region,
self.ordering)
3
Example 28
def to_representation(self, obj):
""" convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.
NB: The argument is whole object, instead of attribute value. This is upstream feature.
Probably because the field can be represented by a complicated method with nontrivial way to extract data.
"""
value = self.model_field.__get__(obj, None)
return smart_text(value, strings_only=True)
3
Example 29
Project: site Source File: select2.py
def get(self, request, *args, **kwargs):
self.request = request
self.term = kwargs.get('term', request.GET.get('term', ''))
self.object_list = self.get_queryset()
context = self.get_context_data()
return JsonResponse({
'results': [
{
'text': smart_text(self.get_name(obj)),
'id': obj.pk,
} for obj in context['object_list']],
'more': context['page_obj'].has_next(),
})
3
Example 30
def __init__(self, source=None, label=None, help_text=None, i18n=False):
self.parent = None
self.creation_counter = Field.creation_counter
Field.creation_counter += 1
self.source = source
if label is not None:
self.label = smart_text(label)
else:
self.label = None
self.help_text = help_text
self._errors = []
self._value = None
self._name = None
self.i18n = i18n
3
Example 31
Project: 2buntu-blog Source File: reference.py
def create_element(self, article):
# Note: only published articles are rendered
if article.status == article.PUBLISHED:
e = markdown.util.etree.Element('a')
e.set('href', article.get_absolute_url())
e.text = smart_text(article)
return e
3
Example 32
def test_encodings(self):
"""Test inbound email with non-UTF8 encoded fields."""
data = test_inbound_payload_1252
request = self.factory.post(self.url, data=data)
email = self.parser.parse(request)
self.assertEqual(email.body, smart_text(data['text']))
3
Example 33
Project: edx-ora2 Source File: filesystem.py
def make_download_url_available(url_key_name, timeout):
"""
Authorize a download URL.
Arguments:
url_key_name (str): key that uniquely identifies the url
timeout (int): time in seconds before the url expires
"""
get_cache().set(
smart_text(get_download_cache_key(url_key_name)),
1, timeout
)
3
Example 34
Project: shuup Source File: writer.py
def get_rendered_output(self):
body = u"".join(conditional_escape(smart_text(piece)) for piece in self.output)
styles = self.styles
extrahead = (self.extra_header or u"")
if self.inline:
template = self.INLINE_TEMPLATE
else:
template = self.TEMPLATE
html = template % {"title": self.title, "body": body, "style": styles, "extrahead": extrahead}
if not self.inline:
html = html.encode("UTF-8")
return html
3
Example 35
def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
self.model.objects.create(
user_id=user_id,
content_type_id=content_type_id,
object_id=smart_text(object_id),
object_repr=object_repr[:200],
action_flag=action_flag,
change_message=change_message,
)
3
Example 36
def handle(self, **options):
permissions, users, warnings = UserenaSignup.objects.check_permissions()
output = options.pop("output")
test = options.pop("test")
if test:
self.stdout.write(40 * ".")
self.stdout.write("\nChecking permission management command. Ignore output..\n\n")
if output:
for p in permissions:
self.stdout.write("Added permission: %s\n" % p)
for u in users:
self.stdout.write("Changed permissions for user: %s\n" % smart_text(u, encoding='utf-8', strings_only=False))
for w in warnings:
self.stdout.write("WARNING: %s\n" %w)
if test:
self.stdout.write("\nFinished testing permissions command.. continuing..\n")
3
Example 37
Project: django-blog-zinnia Source File: test_feeds.py
def test_author_title_non_ascii(self):
self.author.first_name = smart_text('Léon')
self.author.last_name = 'Bloom'
self.author.save()
self.create_published_entry()
feed = AuthorEntries()
self.assertEqual(feed.get_title(self.author),
smart_text('Entries for the author %s' %
self.author.__str__()))
self.assertEqual(feed.description(self.author),
smart_text('The last entries by %s' %
self.author.__str__()))
3
Example 38
Project: django-password-policies Source File: validators.py
def __init__(self, dictionary='', words=[]):
if not dictionary:
self.dictionary = settings.PASSWORD_DICTIONARY
else:
self.dictionary = dictionary
if not words:
self.words = settings.PASSWORD_WORDS
else:
self.words = words
haystacks = []
if self.dictionary:
with open(self.dictionary) as dictionary:
haystacks.extend(
[smart_text(x.strip()) for x in dictionary.readlines()]
)
if self.words:
haystacks.extend(self.words)
super(DictionaryValidator, self).__init__(haystacks=haystacks)
3
Example 39
def writerow(self, row):
row = [smart_text(s) for s in row]
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
3
Example 40
Project: cgstudiomap Source File: context_processors.py
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
return {'csrf_token': SimpleLazyObject(_get_val)}
3
Example 41
Project: django-jet Source File: jet_tags.py
@register.assignment_tag(takes_context=True)
def jet_popup_response_data(context):
if context.get('popup_response_data'):
return context['popup_response_data']
return json.dumps({
'action': context.get('action'),
'value': context.get('value') or context.get('pk_value'),
'obj': smart_text(context.get('obj')),
'new_value': context.get('new_value')
})
3
Example 42
def validate_get(self, request, method):
encode_get_params = lambda r: dict([(k, v[0] if len(v) == 1 else v) for k, v in r])
if request.method == 'GET':
method = smart_text(method)
if method in self.urls and getattr(self.urls[method], 'json_safe',
False):
D = {
'params': encode_get_params(request.GET.lists()),
'method': method,
'id': 'jsonrpc',
'version': '1.1'
}
return True, D
return False, {}
3
Example 43
Project: django-rest-framework-jwt Source File: authentication.py
def get_jwt_value(self, request):
auth = get_authorization_header(request).split()
auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()
if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
return None
if len(auth) == 1:
msg = _('Invalid Authorization header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid Authorization header. Credentials string '
'should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
return auth[1]
3
Example 44
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
3
Example 45
Project: RatticWeb Source File: importloaders.py
def _walkkeepass(groups, entries, groupstack, root):
for n in root.children:
t = smart_text(n.title, errors='replace')
groupstack.append(t)
groups.append(t)
for e in n.entries:
if e.title != 'Meta-Info':
entries.append({
'title': smart_text(e.title, errors='replace'),
'username': smart_text(e.username, errors='replace'),
'password': smart_text(e.password, errors='replace'),
'description': smart_text(e.notes, errors='replace'),
'url': smart_text(e.url, errors='replace'),
'tags': list(groupstack),
'filecontent': e.binary,
'filename': smart_text(e.binary_desc, errors='replace'),
})
_walkkeepass(groups, entries, groupstack, n)
groupstack.pop()
3
Example 46
def to_internal_value(self, data):
if self.queryset is None:
raise Exception('Writable related fields must include a `queryset` argument')
try:
return self.queryset.get(**{self.slug_field: data})
except ObjectDoesNotExist:
opts = ["'" + getattr(obj, self.slug_field) + "'"
for obj in self.queryset.all()]
raise serializers.ValidationError(self.error_messages['does_not_exist'] %
(smart_text(data), ', '.join(opts)))
except (TypeError, ValueError):
msg = self.error_messages['invalid']
raise serializers.ValidationError(msg)
3
Example 47
def log_action(self, user_id, content_type_id, object_id, object_repr,
action_flag, change_message=''):
content_type = ContentType.objects.get(id=content_type_id)
user = User.objects.get(id=user_id)
e = self.model.objects.create(user=user, content_type=content_type,
object_id=smart_text(object_id), action_flag=action_flag,
object_repr=object_repr[:200], change_message=change_message)
3
Example 48
Project: mezzanine Source File: urls.py
def slugify_unicode(s):
"""
Replacement for Django's slugify which allows unicode chars in
slugs, for URLs in Chinese, Russian, etc.
Adopted from https://github.com/mozilla/unicode-slugify/
"""
chars = []
for char in str(smart_text(s)):
cat = unicodedata.category(char)[0]
if cat in "LN" or char in "-_~":
chars.append(char)
elif cat == "Z":
chars.append(" ")
return re.sub("[-\s]+", "-", "".join(chars).strip()).lower()
3
Example 49
Project: django-simple-history Source File: models.py
def get_meta_options(self, model):
"""
Returns a dictionary of fields that will be added to
the Meta inner class of the historical record model.
"""
meta_fields = {
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
}
if self.user_set_verbose_name:
name = self.user_set_verbose_name
else:
name = string_concat('historical ',
smart_text(model._meta.verbose_name))
meta_fields['verbose_name'] = name
return meta_fields
3
Example 50
@property
def description(self):
d = smart_text(self.product)
ops = []
for attribute in self.attributes.all():
ops.append("%s = '%s'" % (attribute.option.name, attribute.value))
if ops:
d = "%s (%s)" % (d, ", ".join(ops))
return d