def display_for_field(value, field): from xadmin.defs import EMPTY_CHANGELIST_VALUE if field.flatchoices: if hasattr(value, '__iter__'): rets = [ dict(field.flatchoices).get(e, EMPTY_CHANGELIST_VALUE) for e in value ] return ','.join(rets) else: 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 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, }
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 = dutils.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)
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, 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 dutils.smart_unicode(o)
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 _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): 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 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 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 self.check_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, }
def help_text_for_field(name, model): try: help_text = model._meta.get_field_by_name(name)[0].help_text except models.FieldDoesNotExist: help_text = "" return smart_unicode(help_text)
def valid_value(self, value): value = self.prepare_value(value) for k, v in self.choices: if value == dutils.smart_unicode(k): return True return False
def result_item(self, obj, field_name, row): """ 返回某一对象某一列的数据, :class:`ResultItem` 实例. :param obj: Model 对象 :param field_name: 列的名字 :param row: :class:`ResultHeader` 实例 """ item = ResultItem(field_name, row) # 首先初始化 field_name_split = field_name.split('.') field_name = field_name_split[0] try: f, attr, value = lookup_field(field_name, obj, self) except (AttributeError, ObjectDoesNotExist): item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE) else: if f is None: # Model 属性或是 OptionClass 属性列 item.allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: item.allow_tags = True item.text = boolean_icon(value) else: item.text = smart_unicode(value) else: # 处理关联咧 if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(obj, f.name) if field_val is None: item.text = mark_safe( "<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE) else: if len(field_name_split) > 1: item.text = getattr(field_val, field_name_split[1]) else: item.text = field_val else: item.text = display_for_field(value, f) if isinstance(f, models.DateField)\ or isinstance(f, models.TimeField)\ or isinstance(f, models.ForeignKey): item.classes.append('nowrap') item.field = f item.attr = attr item.value = value # 如果没有指定 ``list_display_links`` , 使用第一列作为内容连接列. if (item.row['is_display_first'] and not self.list_display_links) \ or field_name in self.list_display_links: item.row['is_display_first'] = False item.is_display_link = True if self.list_display_links_details: url = self.get_detail_url(obj) #item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_name)) #if item_res_uri: # edit_url = self.model_admin_url("change", getattr(obj, self.pk_name)) # item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>' # % (item_res_uri, edit_url, _(u'Details of %s') % str(obj))) else: url = self.get_object_url(obj) if self.pop: if 's' in self.request.GET: show = getattr(obj, self.request.GET.get('s')) if callable(show): show = show() else: show = escape(Truncator(obj).words(14, truncate='...')) show = str(show).replace('%', '%%').replace("\'", "\\\'") pop = format_html( ' class="for_multi_select" show="{0}" sid="{1}" ', show, getattr(obj, self.request.GET.get('t'))) else: pop = '' item.wraps.append(u'<a href="%s" %s>%%s</a>' % (url, pop)) return item