Python django.utils.encoding.smart_unicode() Examples

The following are 30 code examples of django.utils.encoding.smart_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: editable.py    From devops with MIT License 7 votes vote down vote up
def _get_new_field_html(self, field_name):
        try:
            f, attr, value = lookup_field(field_name, self.org_obj, self)
        except (AttributeError, ObjectDoesNotExist):
            return EMPTY_CHANGELIST_VALUE
        else:
            allow_tags = False
            if f is None:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    text = boolean_icon(value)
                else:
                    text = smart_unicode(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(self.org_obj, f.name)
                    if field_val is None:
                        text = EMPTY_CHANGELIST_VALUE
                    else:
                        text = field_val
                else:
                    text = display_for_field(value, f)
            return mark_safe(text) if allow_tags else conditional_escape(text) 
Example #2
Source File: filters.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
def choices(self):
        yield {
            'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val,
            'query_string': self.query_string({},
                                              [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_exact_val == smart_unicode(pk_val),
                'query_string': self.query_string({
                    self.lookup_exact_name: pk_val,
                }, [self.lookup_isnull_name]),
                'display': val,
            }
        if (is_related_field(self.field)
                and self.field.field.null or hasattr(self.field, 'rel')
                and self.field.null):
            yield {
                'selected': bool(self.lookup_isnull_val),
                'query_string': self.query_string({
                    self.lookup_isnull_name: 'True',
                }, [self.lookup_exact_name]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #3
Source File: filters.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
def choices(self):
        yield {
            'selected': (self.lookup_exact_val is '' and self.lookup_isnull_val is ''),
            'query_string': self.query_string({}, [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        include_none = False
        for val in self.lookup_choices:
            if val is None:
                include_none = True
                continue
            val = smart_unicode(val)
            yield {
                'selected': self.lookup_exact_val == val,
                'query_string': self.query_string({self.lookup_exact_name: val},
                                                  [self.lookup_isnull_name]),
                'display': val,
            }
        if include_none:
            yield {
                'selected': bool(self.lookup_isnull_val),
                'query_string': self.query_string({self.lookup_isnull_name: 'True'},
                                                  [self.lookup_exact_name]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #4
Source File: add_missing_image_sizes.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        def patchSize(obj):
            name = smart_unicode(obj.image_file.name)
            path = name
            try:
                obj.size = obj.image_file.storage.size(path)
                obj.save(keep_deleted=True)
            except AttributeError:
                path = os.path.join('images', name)
                try:
                    obj.size = obj.image_file.storage.size(path)
                    obj.save(keep_deleted=True)
                except AttributeError as e:
                    print e

        qs = Image.all_objects.filter(size=0)
        i = 0
        total = qs.count()
        for image in qs:
            patchSize(image)
            i += 1
            for r in ImageRevision.all_objects.filter(image=image, size=0):
                patchSize(r)
            print "%d/%d" % (i, total)
            sleep(0.1) 
Example #5
Source File: filters.py    From devops with MIT License 6 votes vote down vote up
def choices(self):
        yield {
            'selected': (self.lookup_exact_val is '' and self.lookup_isnull_val is ''),
            'query_string': self.query_string({}, [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        include_none = False
        for val in self.lookup_choices:
            if val is None:
                include_none = True
                continue
            val = smart_unicode(val)
            yield {
                'selected': self.lookup_exact_val == val,
                'query_string': self.query_string({self.lookup_exact_name: val},
                                                  [self.lookup_isnull_name]),
                'display': val,
            }
        if include_none:
            yield {
                'selected': bool(self.lookup_isnull_val),
                'query_string': self.query_string({self.lookup_isnull_name: 'True'},
                                                  [self.lookup_exact_name]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #6
Source File: filters.py    From devops with MIT License 6 votes vote down vote up
def choices(self):
        yield {
            'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val,
            'query_string': self.query_string({},
                                              [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_exact_val == smart_unicode(pk_val),
                'query_string': self.query_string({
                    self.lookup_exact_name: pk_val,
                }, [self.lookup_isnull_name]),
                'display': val,
            }
        if (isinstance(self.field, ForeignObjectRel)
                and self.field.field.null or hasattr(self.field, 'rel')
                and self.field.null):
            yield {
                'selected': bool(self.lookup_isnull_val),
                'query_string': self.query_string({
                    self.lookup_isnull_name: 'True',
                }, [self.lookup_exact_name]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #7
Source File: util.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value) 
Example #8
Source File: sudoterminal.py    From devops with GNU General Public License v3.0 6 votes vote down vote up
def _print_exec_out(cmd, out_buf, err_buf, exit_status, channel_name=None ):
        from devops.asgi import channel_layer
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('command executed: {}'.format(cmd))])})
        print('command executed: {}'.format(cmd))
        print('STDOUT:')
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('STDOUT:')])})
        for line in out_buf:
            print line, "end="
            channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode(line.strip('\n'))])})
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('end of STDOUT')])})
        print('end of STDOUT')
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('STDERR:')])})
        print('STDERR:')
        for line in err_buf:
            print line, "end="
            channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode(line, "end=")])})
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('end of STDERR')])})
        print('end of STDERR')
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('finished with exit status: {}'.format(exit_status))])})
        print('finished with exit status: {}'.format(exit_status))
        channel_layer.send(channel_name, {'text': json.dumps(['stdout',smart_unicode('------------------------------------')])})
        print('------------------------------------') 
Example #9
Source File: sudoterminal.py    From devops with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        for server_ip in self.server_list:
            self.message.reply_channel.send({"text":json.dumps(['stdout','\033[1;3;31mExecute task on server:%s \033[0m' %(smart_unicode(server_ip)) ] )},immediately=True)

            #get server credential info
            serverdata = Assets.objects.get(wip=server_ip)
            port = serverdata.ssh_port
            method = serverdata.user.auth_method
            username = serverdata.user.username
            if method == 'ssh-password':
                credential = serverdata.user.password
            else:
                credential = serverdata.user.key


            #do actual job
            ssh = ShellHandler(server_ip,username,port,method,credential,channel_name=self.message.reply_channel.name)
            for command in self.commands:
                ssh.execute(command)
            del ssh 
Example #10
Source File: filters.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def choices(self):
        yield {
            'selected': self.lookup_exact_val is '',
            'query_string': self.query_string({}, [self.lookup_exact_name]),
            'display': _('All')
        }
        for lookup, title in self.field.flatchoices:
            yield {
                'selected': smart_unicode(lookup) == self.lookup_exact_val,
                'query_string': self.query_string({self.lookup_exact_name: lookup}),
                'display': title,
            } 
Example #11
Source File: chart.py    From devops with MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_unicode(o) 
Example #12
Source File: filters.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def choices(self):
        self.lookup_in_val = (type(self.lookup_in_val) in (tuple,list)) and self.lookup_in_val or list(self.lookup_in_val)
        yield {
            'selected': len(self.lookup_in_val) == 0,
            'query_string': self.query_string({},[self.lookup_in_name]),
            'display': _('All'),
        }
        for val in self.lookup_choices:
            yield {
                'selected': smart_unicode(val) in self.lookup_in_val,
                'query_string': self.query_string({self.lookup_in_name: ",".join([val]+self.lookup_in_val),}),
                'remove_query_string': self.query_string({self.lookup_in_name: ",".join([v for v in self.lookup_in_val if v != val]),}),
                'display': val,
            } 
Example #13
Source File: dashboard.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def valid_value(self, value):
        value = self.prepare_value(value)
        for k, v in self.choices:
            if value == smart_unicode(k):
                return True
        return False 
Example #14
Source File: base.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_unicode(o) 
Example #15
Source File: detail.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def init(self):
        self.label = label_for_field(self.field_name, self.obj.__class__,
                                     model_admin=self.admin_view,
                                     return_attr=False
                                     )
        try:
            f, attr, value = lookup_field(
                self.field_name, self.obj, self.admin_view)
        except (AttributeError, ObjectDoesNotExist):
            self.text
        else:
            if f is None:
                self.allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    self.allow_tags = True
                    self.text = boolean_icon(value)
                else:
                    self.text = smart_unicode(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    self.text = getattr(self.obj, f.name)
                else:
                    self.text = display_for_field(value, f)
            self.field = f
            self.attr = attr
            self.value = value 
Example #16
Source File: util.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_unicode(value) 
Example #17
Source File: models.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_unicode(o) 
Example #18
Source File: chart.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_unicode(o) 
Example #19
Source File: export.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                xml.startElement("row", {})
                self._to_xml(xml, item)
                xml.endElement("row")
        elif isinstance(data, dict):
            for key, value in data.iteritems():
                key = key.replace(' ', '_')
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)
        else:
            xml.characters(smart_unicode(data)) 
Example #20
Source File: sudoterminal.py    From webterminal with GNU General Public License v3.0 5 votes vote down vote up
def _print_exec_out(cmd, out_buf, err_buf, exit_status, channel_name=None):
        from webterminal.asgi import channel_layer
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('command executed: {}'.format(cmd))])})
        logger.debug('command executed: {}'.format(cmd))
        logger.debug('STDOUT:')
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('STDOUT:')])})
        for line in out_buf:
            logger.debug(line, "end=")
            channel_layer.send(channel_name, {'text': json.dumps(
                ['stdout', smart_unicode(line.strip('\n'))])})
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('end of STDOUT')])})
        logger.debug('end of STDOUT')
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('STDERR:')])})
        logger.debug('STDERR:')
        for line in err_buf:
            logger.debug(line, "end=")
            channel_layer.send(channel_name, {'text': json.dumps(
                ['stdout', smart_unicode(line, "end=")])})
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('end of STDERR')])})
        logger.debug('end of STDERR')
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('finished with exit status: {}'.format(exit_status))])})
        logger.debug('finished with exit status: {}'.format(exit_status))
        channel_layer.send(channel_name, {'text': json.dumps(
            ['stdout', smart_unicode('------------------------------------')])})
        logger.debug('------------------------------------') 
Example #21
Source File: image.py    From astrobin with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        image = self.get_object()
        alias = kwargs.pop('alias')
        r = kwargs.pop('r')
        opts = {
            'revision_label': r,
            'animated': 'animated' in self.request.GET,
            'insecure': 'insecure' in self.request.GET,
        }

        force = request.GET.get('force')
        if force is not None:
            image.thumbnail_invalidate()

        sync = request.GET.get('sync')
        if sync is not None:
            opts['sync'] = True

        if settings.TESTING:
            thumb = image.thumbnail_raw(alias, opts)
            if thumb:
                return redirect(thumb.url)
            return None

        url = image.thumbnail(alias, opts)
        return redirect(smart_unicode(url)) 
Example #22
Source File: beautifulsoup.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def elem_str(self, elem):
        return smart_unicode(elem) 
Example #23
Source File: html5lib.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def elem_str(self, elem):
        # This method serializes HTML in a way that does not pass all tests.
        # However, this method is only called in tests anyway, so it doesn't
        # really matter.
        return smart_unicode(self._serialize(elem)) 
Example #24
Source File: lxml.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def elem_content(self, elem):
        return smart_unicode(elem.text) 
Example #25
Source File: lxml.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def elem_str(self, elem):
        elem_as_string = smart_unicode(
            self.tostring(elem, method='html', encoding=unicode))
        if elem.tag == 'link':
            # This makes testcases happy
            return elem_as_string.replace('>', ' />')
        return elem_as_string 
Example #26
Source File: default_htmlparser.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def elem_content(self, elem):
        return smart_unicode(elem['text']) 
Example #27
Source File: cache.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _unpack_value(self, value):
        """unpack value, use pickle and/or zlib if necessary"""
        value = self._check_header('zlib', value)
        value = self._check_header('pickle', value)
        if isinstance(value, basestring):
            return smart_unicode(value)
        else:
            return value 
Example #28
Source File: models.py    From django-admino with MIT License 5 votes vote down vote up
def __unicode__(self):
        return smart_unicode(self.name) 
Example #29
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def __unicode__(self):
        return smart_unicode(self.text).title() 
Example #30
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def __unicode__(self):
        return smart_unicode(self.text)