Python django.utils.encoding.force_unicode() Examples

The following are 30 code examples of django.utils.encoding.force_unicode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.encoding , or try the search function .
Example #1
Source File: exceptions.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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] 
Example #2
Source File: util.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
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)
    } 
Example #3
Source File: detail.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: delete.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: list.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: handlers.py    From django-project with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #7
Source File: admin.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #8
Source File: admin.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #9
Source File: delete.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: utils.py    From waliki with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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('/') 
Example #11
Source File: whoosh_cn_backend.py    From thirtylol with MIT License 6 votes vote down vote up
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 
Example #12
Source File: edit.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_breadcrumb(self):
        bcs = super(ModelFormAdminView, self).get_breadcrumb()

        item = {'title': force_unicode(self.org_obj)}
        if self.has_change_permission():
            item['url'] = self.model_admin_url('change', self.org_obj.pk)
        bcs.append(item)

        return bcs 
Example #13
Source File: widgets.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def render(self, name=None, value=None, attrs=None, choices=()):
        name = name or self.name
        value = value or self.value
        attrs = attrs or self.attrs
        attrs['class'] = attrs.get('class', '').replace('form-control', '')
        if 'id' in self.attrs:
            label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
        else:
            label_for = ''
        choice_label = conditional_escape(force_unicode(self.choice_label))
        if attrs.get('inline', False):
            return mark_safe(u'<label%s class="radio-inline">%s %s</label>' % (label_for, self.tag(), choice_label))
        else:
            return mark_safe(u'<div class="radio"><label%s>%s %s</label></div>' % (label_for, self.tag(), choice_label)) 
Example #14
Source File: xversion.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_context(self):
        context = super(RevisionListView, self).get_context()

        opts = self.opts
        action_list = [
            {
                "revision": version.revision,
                "url": self.model_admin_url('revision', quote(version.object_id), version.id),
                "version": version
            }
            for version
            in self._reversion_order_version_queryset(Version.objects.get_for_object_reference(
                self.model,
                self.obj.pk,
            ).select_related("revision__user"))
        ]
        context.update({
            'title': _('Change history: %s') % force_unicode(self.obj),
            'action_list': action_list,
            'model_name': capfirst(force_unicode(opts.verbose_name_plural)),
            'object': self.obj,
            'app_label': opts.app_label,
            "changelist_url": self.model_admin_url("changelist"),
            "update_url": self.model_admin_url("change", self.obj.pk),
            'opts': opts,
        })
        return context 
Example #15
Source File: editable.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def init_request(self, object_id, *args, **kwargs):
        self.org_obj = self.get_object(unquote(object_id))

        # For list view get new field display html
        self.pk_attname = self.opts.pk.attname

        if not self.has_change_permission(self.org_obj):
            raise PermissionDenied

        if self.org_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)}) 
Example #16
Source File: relate.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_brand_name(self):
        if len(self.to_objs) == 1:
            to_model_name = str(self.to_objs[0])
        else:
            to_model_name = force_unicode(self.to_model._meta.verbose_name)

        return mark_safe(u"<span class='rel-brand'>%s <i class='fa fa-caret-right'></i></span> %s" % (to_model_name, force_unicode(self.opts.verbose_name_plural))) 
Example #17
Source File: multiselect.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def render_opt(self, selected_choices, option_value, option_label):
        option_value = force_unicode(option_value)
        return u'<option value="%s">%s</option>' % (
            escape(option_value), conditional_escape(force_unicode(option_label))), bool(option_value in selected_choices) 
Example #18
Source File: xversion.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def post_response(self):
        self.message_user(_('The %(model)s "%(name)s" was recovered successfully. You may edit it again below.') %
                          {"model": force_unicode(self.opts.verbose_name), "name": unicode(self.new_obj)}, 'success')
        return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk)) 
Example #19
Source File: xversion.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def post_response(self):
        self.message_user(_('The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') %
                          {"model": force_unicode(self.opts.verbose_name), "name": unicode(self.new_obj)}, 'success')
        return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk)) 
Example #20
Source File: actions.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def action_checkbox(obj):
    return checkbox.render(ACTION_CHECKBOX_NAME, force_unicode(obj.pk)) 
Example #21
Source File: edit.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_context(self):
        new_context = {
            'title': _('Change %s') % force_unicode(self.org_obj),
            'object_id': str(self.org_obj.pk),
        }
        context = super(UpdateAdminView, self).get_context()
        context.update(new_context)
        return context 
Example #22
Source File: edit.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def post_response(self):
        """
        Determines the HttpResponse for the add_view stage.
        """
        request = self.request

        msg = _(
            'The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(self.opts.verbose_name),
                                                                 'obj': "<a class='alert-link' href='%s'>%s</a>" % (self.model_admin_url('change', self.new_obj._get_pk_val()), force_unicode(self.new_obj))}

        if "_continue" in request.POST:
            self.message_user(
                msg + ' ' + _("You may edit it again below."), 'success')
            return self.model_admin_url('change', self.new_obj._get_pk_val())

        if "_addanother" in request.POST:
            self.message_user(msg + ' ' + (_("You may add another %s below.") % force_unicode(self.opts.verbose_name)), 'success')
            return request.path
        else:
            self.message_user(msg, 'success')

            # Figure out where to redirect. If the user has change permission,
            # redirect to the change-list page for this object. Otherwise,
            # redirect to the admin index.
            if "_redirect" in request.POST:
                return request.POST["_redirect"]
            elif self.has_view_permission():
                return self.model_admin_url('changelist')
            else:
                return self.get_admin_url('index') 
Example #23
Source File: edit.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_breadcrumb(self):
        bcs = super(ModelFormAdminView, self).get_breadcrumb()
        item = {'title': _('Add %s') % force_unicode(self.opts.verbose_name)}
        if self.has_add_permission():
            item['url'] = self.model_admin_url('add')
        bcs.append(item)
        return bcs 
Example #24
Source File: edit.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_context(self):
        new_context = {
            'title': _('Add %s') % force_unicode(self.opts.verbose_name),
        }
        context = super(CreateAdminView, self).get_context()
        context.update(new_context)
        return context 
Example #25
Source File: detail.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_breadcrumb(self):
        bcs = super(DetailAdminView, self).get_breadcrumb()
        item = {'title': force_unicode(self.obj)}
        if self.has_view_permission():
            item['url'] = self.model_admin_url('detail', self.obj.pk)
        bcs.append(item)
        return bcs 
Example #26
Source File: serializers.py    From django-admino with MIT License 5 votes vote down vote up
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 
Example #27
Source File: detail.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def val(self):
        text = mark_safe(
            self.text) if self.allow_tags else conditional_escape(self.text)
        if force_unicode(text) == '' or text == 'None' or text == EMPTY_CHANGELIST_VALUE:
            text = mark_safe(
                '<span class="text-muted">%s</span>' % EMPTY_CHANGELIST_VALUE)
        for wrap in self.wraps:
            text = mark_safe(wrap % text)
        return text 
Example #28
Source File: delete.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def post_response(self):

        self.message_user(_('The %(name)s "%(obj)s" was deleted successfully.') %
                          {'name': force_unicode(self.opts.verbose_name), 'obj': force_unicode(self.obj)}, 'success')

        if not self.has_view_permission():
            return self.get_admin_url('index')
        return self.model_admin_url('changelist') 
Example #29
Source File: models.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        return force_text(self.site) 
Example #30
Source File: delete.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_breadcrumb(self):
        bcs = super(DeleteAdminView, self).get_breadcrumb()
        bcs.append({
            'title': force_unicode(self.obj),
            'url': self.get_object_url(self.obj)
        })
        item = {'title': _('Delete')}
        if self.has_delete_permission():
            item['url'] = self.model_admin_url('delete', self.obj.pk)
        bcs.append(item)

        return bcs