python类force_unicode()的实例源码

widgets.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs=None):

        # Prepare values
        attrs = self.build_attrs(attrs, name=name)
        if not value:
            value = ''

        options = getattr(settings, 'MARKEDIT_DEFAULT_SETTINGS', {})

        if 'options' in attrs:
            options = self._eval_value(attrs['options'], {})
            del attrs['options']

        # Render widget to HTML
        t = loader.get_template('markedit/ui.html')
        c = Context({
            'attributes': self._render_attrs(attrs),
            'value': conditional_escape(force_unicode(value)),
            'id': attrs['id'],
            'options': options,
        })

        return t.render(c)
delete.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
delete.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
    }
utils.py 文件源码 项目:basket 作者: mozmeao 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def process_email(email):
    """Validates that the email is valid.

    Return email ascii encoded if valid, None if not.
    """
    if not email:
        return None

    email = force_unicode(email)
    try:
        # NOTE SFDC doesn't support SMPTUTF8, so we cannot enable support
        #      here until they do or we switch providers
        info = validate_email(email, allow_smtputf8=False,
                              check_deliverability=False)
    except EmailNotValidError:
        return None

    return info.get('email_ascii', None)
delete.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
delete.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
    }
widgets.py 文件源码 项目:xadmin-markdown-editor 作者: bluenknight 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs=None):
        if value is None:
            value = ""
        if VERSION < (1, 11):
            final_attrs = self.build_attrs(attrs, name=name)
        else:
            final_attrs = self.build_attrs(attrs, {'name': name})

        if "class" not in final_attrs:
            final_attrs["class"] = ""
        final_attrs["class"] += " wmd-input"
        template = loader.get_template(self.template)

        # Compatibility fix:
        # see https://github.com/timmyomahony/django-pagedown/issues/42
        context = {
            "attrs": flatatt(final_attrs),
            "body": conditional_escape(force_unicode(value)),
            "id": final_attrs["id"],
            "show_preview": self.show_preview,
        }
        context = Context(context) if VERSION < (1, 9) else context
        return template.render(context)
utils.py 文件源码 项目:django-twilio-tfa 作者: rtindru 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def serialize_instance(instance):
    """
    Since Django 1.6 items added to the session are no longer pickled,
    but JSON encoded by default. We are storing partially complete models
    in the session (user, account, token, ...). We cannot use standard
    Django serialization, as these are models are not "complete" yet.
    Serialization will start complaining about missing relations et al.
    """
    data = {}
    for k, v in instance.__dict__.items():
        if k.startswith('_') or callable(v):
            continue
        try:
            if isinstance(instance._meta.get_field(k), BinaryField):
                v = force_text(base64.b64encode(v))
        except FieldDoesNotExist:
            pass
        data[k] = v
    return json.loads(json.dumps(data, cls=DjangoJSONEncoder))
edit.py 文件源码 项目:YouPBX 作者: JoneXiong 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_context(self):
        """
        **Context Params**:

            ``title`` : ????

            ``object_id`` : ???????? id
        """
        new_context = {
            'title': _('Change %s') % force_unicode(self.org_obj),
            'object_id': str(self.org_obj.pk),
            'cl': self
        }
        context = super(UpdateAdminView, self).get_context()
        context.update(new_context)
        return context
detail.py 文件源码 项目:YouPBX 作者: JoneXiong 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_context(self):
        """
        **Context Params** :

            ``form`` : ??????? Form ??

            ``object`` : ???? Model ??
        """
        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
delete.py 文件源码 项目:YouPBX 作者: JoneXiong 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def init_request(self, object_id, *args, **kwargs):
        """
        ??????????? ``object_id`` ????????????????????
        """
        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)    # ????db
        # ?? deleted_objects, ??????????????
        (self.deleted_objects, self.perms_needed, self.protected) = get_deleted_objects(
            [self.obj], self.opts, self.request.user, self.admin_site, using)
util.py 文件源码 项目:YouPBX 作者: JoneXiong 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
    }
delete.py 文件源码 项目:eduDjango 作者: yuzhou6 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
delete.py 文件源码 项目:eduDjango 作者: yuzhou6 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:eduDjango 作者: yuzhou6 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
    }
delete.py 文件源码 项目:Django-IMOOC-Shop 作者: LBruse 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
delete.py 文件源码 项目:Django-IMOOC-Shop 作者: LBruse 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:Django-IMOOC-Shop 作者: LBruse 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
    }
__init__.py 文件源码 项目:webtzite 作者: materialsproject 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def default(self, obj):
        if isinstance(obj, bson.objectid.ObjectId):
            return force_unicode(obj)
        return super(MongoJSONEncoder, self).default(obj)
text.py 文件源码 项目:django-bootstrap4 作者: zostera 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def text_value(value):
    """
    Force a value to text, render None as an empty string
    """
    if value is None:
        return ''
    return force_text(value)
generate_filename.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def by_date(instance, filename):
    datepart = force_text(now().strftime("%Y/%m/%d"))
    return os.path.join(datepart, get_valid_filename(filename))
serializers.py 文件源码 项目:django-admino 作者: erdem 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
json.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def default(self, obj):
        if (isinstance(obj, datetime.datetime) or
            isinstance(obj, datetime.date) or
            isinstance(obj, datetime.time)):
            return int(dateformat.format(obj, 'U'))

        try:
            return super(PootleJSONEncoder, self).default(obj)
        except TypeError:
            return force_unicode(obj)
errorpages.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def handle_exception(request, exception, template_name):
    # XXX: remove this? exceptions are already displayed in debug mode
    tb = traceback.format_exc()
    print >> sys.stderr, tb

    if settings.DEBUG:
        return None

    try:
        log_exception(request, exception, tb)

        msg = force_unicode(exception)

        if request.is_ajax():
            return JsonResponseServerError({'msg': msg})

        ctx = {
            'exception': msg,
        }
        if hasattr(exception, 'filename'):
            msg_args = {
                'filename': exception.filename,
                'errormsg': exception.strerror,
            }
            msg = _('Error accessing %(filename)s, Filesystem '
                    'sent error: %(errormsg)s', msg_args)
            ctx['fserror'] = msg

        return HttpResponseServerError(
            render_to_string(template_name, context=ctx, request=request)
        )
    except:
        # Let's not confuse things by throwing an exception here
        pass
errorpages.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def process_exception(self, request, exception):
        msg = force_unicode(exception)
        if isinstance(exception, Http404):
            if request.is_ajax():
                return JsonResponseNotFound({'msg': msg})
        elif isinstance(exception, Http400):
            if request.is_ajax():
                return JsonResponseBadRequest({'msg': msg})
        elif isinstance(exception, PermissionDenied):
            if request.is_ajax():
                return JsonResponseForbidden({'msg': msg})

            ctx = {
                'permission_error': msg,
            }

            if not request.user.is_authenticated:
                msg_args = {
                    'login_link': reverse('account_login'),
                }
                login_msg = _(
                    'You need to <a class="js-login" '
                    'href="%(login_link)s">login</a> to access this page.',
                    msg_args
                )
                ctx["login_message"] = login_msg

            return HttpResponseForbidden(
                render_to_string('errors/403.html', context=ctx,
                                 request=request))
        elif (exception.__class__.__name__ in
                ('OperationalError', 'ProgrammingError', 'DatabaseError')):
            # HACKISH: Since exceptions thrown by different databases do not
            # share the same class heirarchy (DBAPI2 sucks) we have to check
            # the class name instead. Since python uses duck typing I will call
            # this poking-the-duck-until-it-quacks-like-a-duck-test
            return handle_exception(request, exception, 'errors/db.html')
        else:
            return handle_exception(request, exception, 'errors/500.html')
adapter.py 文件源码 项目:django-actistream 作者: pennersr 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def format_email_subject(self, subject):
        prefix = getattr(settings, 'ACTISTREAM_EMAIL_SUBJECT_PREFIX', None)
        if prefix is None:
            site = self.get_current_site()
            if site:
                prefix = "[{name}] ".format(name=site.name)
            else:
                prefix = ''
        return prefix + force_text(subject)
widgets.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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))
widgets.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def render(self):
        return mark_safe(u'\n'.join([force_unicode(w) for w in self]))


问题


面经


文章

微信
公众号

扫码关注公众号