当前位置: 首页>>代码示例>>Python>>正文


Python encoding.force_unicode方法代码示例

本文整理汇总了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('/') 
开发者ID:mgaitan,项目名称:waliki,代码行数:18,代码来源:utils.py

示例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 
开发者ID:infinity1207,项目名称:thirtylol,代码行数:24,代码来源:whoosh_cn_backend.py

示例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)) 
开发者ID:django-leonardo,项目名称:django-leonardo,代码行数:25,代码来源:admin.py

示例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(("&nbsp;&nbsp;" * 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 
开发者ID:django-leonardo,项目名称:django-leonardo,代码行数:18,代码来源:admin.py

示例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 
开发者ID:peragro,项目名称:django-project,代码行数:24,代码来源:handlers.py

示例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 
开发者ID:Liweimin0512,项目名称:ImitationTmall_Django,代码行数:27,代码来源:list.py

示例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) 
开发者ID:Liweimin0512,项目名称:ImitationTmall_Django,代码行数:18,代码来源:delete.py

示例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 
开发者ID:Liweimin0512,项目名称:ImitationTmall_Django,代码行数:19,代码来源:delete.py

示例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 
开发者ID:Liweimin0512,项目名称:ImitationTmall_Django,代码行数:18,代码来源:detail.py

示例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)
    } 
开发者ID:Liweimin0512,项目名称:ImitationTmall_Django,代码行数:20,代码来源:util.py

示例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] 
开发者ID:canvasnetworks,项目名称:canvas,代码行数:19,代码来源:exceptions.py

示例12: __str__

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_unicode [as 别名]
def __str__(self):
        return force_text(self.site) 
开发者ID:mishbahr,项目名称:django-usersettings2,代码行数:4,代码来源:models.py

示例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 
开发者ID:erdem,项目名称:django-admino,代码行数:33,代码来源:serializers.py

示例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 
开发者ID:infinity1207,项目名称:thirtylol,代码行数:30,代码来源:whoosh_cn_backend.py

示例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')) 
开发者ID:infinity1207,项目名称:thirtylol,代码行数:7,代码来源:whoosh_cn_backend.py


注:本文中的django.utils.encoding.force_unicode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。