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,
}
python类smart_unicode()的实例源码
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)
def __init__(self, title, url, acl_groups=None, acl_perms=None, absolute_url=False, menu=None):
self.title = smart_unicode(title)
self._url = url
self._url_is_resolved = absolute_url
self.absolute_url = absolute_url
self.acl_groups = acl_groups and set(acl_groups) or set()
self.acl_perms = acl_perms and set(acl_perms) or set()
self.main_menu = None
self.parent_menu = None
self.alters_data = False
self.submenu_list = []
for i in menu or []:
if type(i) in (tuple, list):
self.submenu_list.extend(i)
else:
self.submenu_list.append(i)
self.active = False
self.depth = 0
def label_for_value(self, value):
values = value.split(',')
str_values = []
key = self.rel.get_related_field().name
app_label = self.rel.to._meta.app_label
class_name = self.rel.to._meta.object_name.lower()
for v in values:
try:
obj = self.rel.to._default_manager.using(self.db).get(**{key: v})
url = reverse('admin:{0}_{1}_change'.format(app_label, class_name), args=[obj.id])
label = escape(smart_unicode(obj))
x = u'<a href="{0}" {1}>{2}</a>'.format(url,
'onclick="return showAddAnotherPopup(this);" target="_blank"',
label
)
str_values += [x]
except self.rel.to.DoesNotExist:
str_values += [u'???']
return u' <strong>{0}</strong>'.format(u', '.join(str_values))
def render(self, name, value, attrs=None, choices=(), *args, **kwargs):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<select {0}>'.format(flatatt(final_attrs))]
str_value = smart_unicode(value)
for group_label, group in self.choices:
if group_label:
# should belong to an optgroup
group_label = smart_unicode(group_label)
output.append(u'<optgroup label="%s">' % escape(group_label))
for key, value in group:
#build option html
option_value = smart_unicode(key)
output.append(
u'<option value="{0}"{1}>{2}</option>'.format(
escape(option_value),
(option_value == str_value) and u' selected="selected"' or '',
escape(smart_unicode(value))
)
)
if group_label:
output.append(u'</optgroup>')
output.append(u'</select>')
return u'\n'.join(output)
def clean(self, value):
"""
Validates that the input is in self.choices.
"""
value = super(GroupedChoiceField, self).clean(value)
if value in (None, ''):
value = u''
value = forms.util.smart_unicode(value)
if value == u'':
return value
valid_values = []
for choice in self.choices:
group = choice[1]
valid_values += [str(key) for key, value in group]
if value not in valid_values:
raise ValidationError(_(u'Select a valid choice. That choice is not one of the available choices.'))
return value
def __init__(self, template_string, name='<Unknown Template>',
libraries=[]):
try:
template_string = encoding.smart_unicode(template_string)
except UnicodeDecodeError:
raise template.TemplateEncodingError(
"template content must be unicode or UTF-8 string")
origin = template.StringOrigin(template_string)
self.nodelist = self.my_compile_string(template_string, origin,
libraries)
self.name = name
def __unicode__(self):
return smart_unicode(self.name)
def __unicode__(self):
return smart_unicode(self.name)
def __unicode__(self):
return smart_unicode(self.name)
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,
}
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,
}
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
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)
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)
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)
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)
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))
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,
}
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,
}