本文整理汇总了Python中django.utils.encoding.force_unicode方法的典型用法代码示例。如果您正苦于以下问题:Python encoding.force_unicode方法的具体用法?Python encoding.force_unicode怎么用?Python encoding.force_unicode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.encoding
的用法示例。
在下文中一共展示了encoding.force_unicode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_slug
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def get_slug(text):
def slugify(value):
"""
same than django slugify but allowing uppercase and underscore
"""
value = force_text(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s\/_-]', '', value).strip()
return mark_safe(re.sub('[-\s]+', '-', value))
if PY2:
from django.utils.encoding import force_unicode
text = force_unicode(text)
for sep in ('_', '/'):
text = sep.join(slugify(t) for t in text.split(sep))
return text.strip('/')
示例2: _from_python
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def _from_python(self, value):
"""
Converts Python values to a string for Whoosh.
Code courtesy of pysolr.
"""
if hasattr(value, 'strftime'):
if not hasattr(value, 'hour'):
value = datetime(value.year, value.month, value.day, 0, 0, 0)
elif isinstance(value, bool):
if value:
value = 'true'
else:
value = 'false'
elif isinstance(value, (list, tuple)):
value = u','.join([force_text(v) for v in value])
elif isinstance(value, (six.integer_types, float)):
# Leave it alone.
pass
else:
value = force_text(value)
return value
示例3: _format_callback
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def _format_callback(self, obj, user, admin_site, perms_needed):
has_admin = obj.__class__ in admin_site._registry
opts = obj._meta
if has_admin:
admin_url = reverse('%s:%s_%s_change'
% (admin_site.name,
opts.app_label,
opts.object_name.lower()),
None, (quote(obj._get_pk_val()),))
p = '%s.%s' % (opts.app_label,
get_delete_permission(opts))
if not user.has_perm(p):
perms_needed.add(opts.verbose_name)
# Display a link to the admin page.
return mark_safe('%s: <a href="%s">%s</a>' %
(escape(capfirst(opts.verbose_name)),
admin_url,
escape(obj)))
else:
# Don't display link to edit, because it either has no
# admin or is edited inline.
return '%s: %s' % (capfirst(opts.verbose_name),
force_text(obj))
示例4: _list_all_destination_folders_recursive
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def _list_all_destination_folders_recursive(self, request, folders_queryset, current_folder, folders, allow_self, level):
for fo in folders:
if not allow_self and fo in folders_queryset:
# We do not allow moving to selected folders or their
# descendants
continue
if not fo.has_read_permission(request):
continue
# We do not allow copying/moving back to the folder itself
enabled = (
allow_self or fo != current_folder) and fo.has_add_children_permission(request)
yield (fo, (mark_safe((" " * level) + force_text(fo)), enabled))
for c in self._list_all_destination_folders_recursive(request, folders_queryset, current_folder, fo.media_folder_children.all(), allow_self, level + 1):
yield c
示例5: commented_handler
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def commented_handler(instance, comment, **kwargs):
for follow in Follow.objects.get_follows(instance):
notify.send(instance.author,
recipient=follow.user,
actor=instance.author,
verb='commented',
action_object=comment,
description=comment.comment[:50]+'...',
target=instance)
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin.models import LogEntry, ADDITION
from django.utils.encoding import force_unicode
LogEntry.objects.log_action(
user_id = instance.author.pk,
content_type_id = ContentType.objects.get_for_model(comment).pk,
object_id = comment.pk,
object_repr = force_unicode(comment),
action_flag = ADDITION
)
# connect the signal
示例6: get_context
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def get_context(self):
"""
Prepare the context for templates.
"""
self.title = _('%s List') % force_unicode(self.opts.verbose_name)
model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f))
for f in (list(self.opts.fields) + self.get_model_method_fields()) if f.name not in self.list_exclude]
new_context = {
'model_name': force_unicode(self.opts.verbose_name_plural),
'title': self.title,
'cl': self,
'model_fields': model_fields,
'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]),
'has_add_permission': self.has_add_permission(),
'app_label': self.app_label,
'brand_name': self.opts.verbose_name_plural,
'brand_icon': self.get_model_icon(self.model),
'add_url': self.model_admin_url('add'),
'result_headers': self.result_headers(),
'results': self.results()
}
context = super(ListAdminView, self).get_context()
context.update(new_context)
return context
示例7: init_request
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
示例8: get_context
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def get_context(self):
if self.perms_needed or self.protected:
title = _("Cannot delete %(name)s") % {"name":
force_unicode(self.opts.verbose_name)}
else:
title = _("Are you sure?")
new_context = {
"title": title,
"object": self.obj,
"deleted_objects": self.deleted_objects,
"perms_lacking": self.perms_needed,
"protected": self.protected,
}
context = super(DeleteAdminView, self).get_context()
context.update(new_context)
return context
示例9: get_context
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def get_context(self):
new_context = {
'title': _('%s Detail') % force_unicode(self.opts.verbose_name),
'form': self.form_obj,
'object': self.obj,
'has_change_permission': self.has_change_permission(self.obj),
'has_delete_permission': self.has_delete_permission(self.obj),
'content_type_id': ContentType.objects.get_for_model(self.model).id,
}
context = super(DetailAdminView, self).get_context()
context.update(new_context)
return context
示例10: model_format_dict
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def model_format_dict(obj):
"""
Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
typically for use with string formatting.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
"""
if isinstance(obj, (models.Model, models.base.ModelBase)):
opts = obj._meta
elif isinstance(obj, models.query.QuerySet):
opts = obj.model._meta
else:
opts = obj
return {
'verbose_name': force_unicode(opts.verbose_name),
'verbose_name_plural': force_unicode(opts.verbose_name_plural)
}
示例11: __init__
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def __init__(self, message, code=None, params=None):
""" ValidationError can be passed any object that can be printed (usually a string), or a dictionary. """
import operator
from django.utils.encoding import force_unicode
if isinstance(message, dict):
self.message_dict = message
self.messages = []
# Reduce each list of messages into a single list.
if message:
message = reduce(operator.add, message.values())
self.messages = [force_unicode(msg) for msg in message]
else:
self.code = code
self.params = params
message = force_unicode(message)
self.messages = [message]
示例12: __str__
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def __str__(self):
return force_text(self.site)
示例13: obj_as_dict
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def obj_as_dict(o):
if isinstance(o, DeclarativeFieldsMetaclass):
o = FormSerializer(form=o).data
if isinstance(o, forms.Field):
o = FormFieldSerializer(field=o).data
if isinstance(o, forms.Widget):
o = FormWidgetSerializer(widget=o).data
if isinstance(o, (list, tuple)):
o = [obj_as_dict(x) for x in o]
if isinstance(o, Promise):
try:
o = force_unicode(o)
except:
# Item could be a lazy tuple or list
try:
o = [obj_as_dict(x) for x in o]
except:
raise Exception('Unable to resolve lazy object %s' % o)
if callable(o):
o = o()
if isinstance(o, dict):
for k, v in o.items():
o[k] = obj_as_dict(v)
return o
示例14: create_spelling_suggestion
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def create_spelling_suggestion(self, query_string):
spelling_suggestion = None
reader = self.index.reader()
corrector = reader.corrector(self.content_field_name)
cleaned_query = force_text(query_string)
if not query_string:
return spelling_suggestion
# Clean the string.
for rev_word in self.RESERVED_WORDS:
cleaned_query = cleaned_query.replace(rev_word, '')
for rev_char in self.RESERVED_CHARACTERS:
cleaned_query = cleaned_query.replace(rev_char, '')
# Break it down.
query_words = cleaned_query.split()
suggested_words = []
for word in query_words:
suggestions = corrector.suggest(word, limit=1)
if len(suggestions) > 0:
suggested_words.append(suggestions[0])
spelling_suggestion = ' '.join(suggested_words)
return spelling_suggestion
示例15: _convert_datetime
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def _convert_datetime(self, date):
if hasattr(date, 'hour'):
return force_text(date.strftime('%Y%m%d%H%M%S'))
else:
return force_text(date.strftime('%Y%m%d000000'))