def djmoney_contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = get_empty_value_display(self) else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: if value is None: result_repr = get_empty_value_display(self) elif isinstance(f.rel, ManyToManyRel): result_repr = ", ".join(map(str, value.all())) else: result_repr = smart_unicode(value) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field, self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE elif isinstance(f.rel, ManyToManyRel): result_repr = ", ".join(map(unicode, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main 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.DateField) or isinstance(field, models.TimeField): if value: date_format = formats.get_format('DATE_FORMAT') datetime_format = formats.get_format('DATETIME_FORMAT') time_format = formats.get_format('TIME_FORMAT') if isinstance(field, models.DateTimeField): return capfirst(dateformat.format(value, datetime_format)) elif isinstance(field, models.TimeField): return capfirst(dateformat.time_format(value, time_format)) else: return capfirst(dateformat.format(value, date_format)) else: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DecimalField): if value is not None: return ('%%.%sf' % field.decimal_places) % value else: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.FloatField): return escape(value) else: return smart_str(value)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main 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(timezone.template_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, models.FileField) and value: return mark_safe('<a href="%s">%s</a>' % ( conditional_escape(value.url), conditional_escape(value), )) else: return smart_text(value)
def get_registrations_link(self, obj): icon = False approved_registrations_count = obj.approved_registrations.count() unapproved_registrations_count = obj.unapproved_registrations.count() if approved_registrations_count == 0: title = _('There are no approved registrations for this {}.').format(obj.subject_type.name_akuzativ) elif obj.min_count is not None and approved_registrations_count < obj.min_count: title = _('The number of approved registrations is lower than {}.').format(obj.min_count) elif obj.max_count is not None and approved_registrations_count > obj.max_count: title = _('The number of approved registrations is greater than {}.').format(obj.max_count) else: icon = True title = '' return format_html( '<a href="{url}" title="{title}">{icon} {approved}{unapproved}</a>', url = reverse('admin:{}_{}_changelist'.format( self.registration_model._meta.app_label, self.registration_model._meta.model_name, )) + '?subject__id__exact={}'.format(obj.id), title = title, icon = _boolean_icon(icon), approved = approved_registrations_count, unapproved = ' + {}'.format(unapproved_registrations_count) if unapproved_registrations_count else '', ) + format_html( '<a class="popup-link" href="{url}" style="background-position: 0 0" title="{title}">' '<img src="{icon}" alt="+"/></a>', url = reverse('admin:{}_{}_add'.format( self.registration_model._meta.app_label, self.registration_model._meta.model_name, )) + '?subject={}'.format(obj.id), title = _('add registration'), icon = static('admin/img/icon-addlink.svg'), )
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): warnings.warn( "Deprecated allow_tags attribute used on %s. " "Use django.utils.safestring.format_html(), " "format_html_join(), or mark_safe() instead." % attr, RemovedInDjango20Warning ) result_repr = mark_safe(value) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def get_field_contents(self, field, obj): from django.contrib.admin.templatetags.admin_list import _boolean_icon model_admin = self try: f, attr, value = lookup_field(field, obj, self) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = get_empty_value_display(self) else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.rel, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, "") return conditional_escape(result_repr)
def djmoney_display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE try: 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(timezone.localtime(value)) elif isinstance(field, models.DateField) or isinstance(field, 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) else: return smart_unicode(value) except: return smart_unicode(value)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if field in self.form.fields: widget = self.form[field].field.widget # This isn't elegant but suffices for contrib.auth's # ReadOnlyPasswordHashWidget. if getattr(widget, 'read_only', False): return widget.render(field, value) if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def is_tutor_with_title(self, obj): """If the person is a tutor the tutor_for tag is set as image title""" if obj.is_tutor == True and obj.tutor_for is not None: icon_url = static('admin/img/icon-yes.svg') return format_html('<img src="{}" alt="{}" title="{}" /> {}', icon_url, obj.is_tutor, obj.tutor_for.name, obj.tutor_for.name) else: return _boolean_icon(obj.is_tutor)
def contents(self, obj): contents = BlogEntryContent.objects.filter(entry=obj) for entry in contents: entry.is_public_html = _boolean_icon(entry.is_public) context = { "contents": contents } return render_to_string("admin/blog/entry_contents.html", context)
def __init__(self, slice, queryset, *args, **kwargs): super(SliverIfaceBulkForm, self).__init__(*args, **kwargs) for iface_type, iface_object in Sliver.get_registered_ifaces().items(): kwargs = { 'label': iface_type, 'required': False, 'help_text': iface_object.__doc__.strip() } if iface_object.ALLOW_BULK and iface_object.is_allowed(slice, queryset): if iface_object.AUTO_CREATE: kwargs['initial'] = _boolean_icon(True) kwargs['widget'] = ShowText() if iface_object.CREATE_BY_DEFAULT: kwargs['initial'] = True else: kwargs['initial'] = _boolean_icon(False) kwargs['widget'] = ShowText() kwargs['label'] += ' (%s)' % iface_object.VERBOSE_DISABLED_MSG self.fields[iface_type] = forms.BooleanField(**kwargs)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(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 field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) else: return smart_unicode(value)
def display_for_value(value, empty_value_display, boolean=False): from django.contrib.admin.templatetags.admin_list import _boolean_icon if boolean: return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, six.integer_types + (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
def display_for_value(value, boolean=False): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main 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(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, six.integer_types + (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
def _get_non_field_repr(cl, result, field_name): """ Render the visual representation of a column which does not refer to a field in the model """ # For non-field list_display values, the value is either: # - a method # - a attribute of the ModelAdmin # - a property or method of the model. try: if callable(field_name): attr = field_name value = attr(result) elif hasattr(cl.model_admin, field_name) and not field_name in ('__str__', '__unicode__'): attr = getattr(cl.model_admin, field_name) value = attr(result) else: attr = getattr(result, field_name) if callable(attr): value = attr() else: value = attr # Parse special attributes of the item allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) elif isinstance(value, SafeData): allow_tags = True result_repr = value else: result_repr = smart_text(value) except (AttributeError, ObjectDoesNotExist): result_repr = get_empty_value_display(cl) else: # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) return result_repr, None
def display_for_value(value, empty_value_display, boolean=False): from django.contrib.admin.templatetags.admin_list import _boolean_icon if boolean: return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, six.integer_types + (decimal.Decimal, float)): return formats.number_format(value) elif isinstance(value, (list, tuple)): return ', '.join(force_text(v) for v in value) else: return force_text(value)
def display_for_value(value, empty_value_display, boolean=False): from django.contrib.admin.templatetags.admin_list import _boolean_icon if boolean: return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (int, decimal.Decimal, float)): return formats.number_format(value) elif isinstance(value, (list, tuple)): return ', '.join(str(v) for v in value) else: return str(value)
def _get_non_field_repr(cl, result, field_name): """ Render the visual representation of a column which does not refer to a field in the model """ # For non-field list_display values, the value is either: # - a method # - a attribute of the ModelAdmin # - a property or method of the model. try: if callable(field_name): attr = field_name value = attr(result) elif hasattr(cl.model_admin, field_name) and not field_name in ('__str__', '__unicode__'): attr = getattr(cl.model_admin, field_name) value = attr(result) else: attr = getattr(result, field_name) if callable(attr): value = attr() else: value = attr # Parse special attributes of the item allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) elif isinstance(value, SafeData): allow_tags = True result_repr = value else: result_repr = smart_text(value) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) return result_repr, None
def display_for_value(value, boolean=False): # pragma: no cover """ Added for compatibility with django 1.4, copied from django trunk. """ from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main 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(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, six.integer_types + (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
def display_for_value(value, boolean=False): # pragma: no cover """ Added for compatibility with django 1.4, copied from django trunk. """ from django.contrib.admin.templatetags.admin_list import _boolean_icon # from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if boolean: return _boolean_icon(value) elif value is None: # return EMPTY_CHANGELIST_VALUE return get_empty_value_display() elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, six.integer_types + (decimal.Decimal, float)): return formats.number_format(value) else: return smart_text(value)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateField) or isinstance( field, models.TimeField): return formats.localize(value) elif isinstance(field, models.BooleanField) or isinstance( field, models.NullBooleanField): return _boolean_icon(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) else: return smart_unicode(value)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main 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. if isinstance(field, fields.BooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, fields.DateTimeField): return formats.localize(value) elif isinstance(field, fields.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, fields.FloatField): return formats.number_format(value) else: return smart_text(value)
def display_for_field(value, field, empty_value_display): from django.contrib.admin.templatetags.admin_list import _boolean_icon if field.flatchoices: return dict(field.flatchoices).get(value, empty_value_display) # 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_value_display elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): if isinstance(field, models.DateTimeField): value = timezone.localtime(value) 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) else: return smart_text(value)
def display_for_field(value, field, empty_value_display): from django.contrib.admin.templatetags.admin_list import _boolean_icon if field.flatchoices: return dict(field.flatchoices).get(value, empty_value_display) # 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_value_display elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): if isinstance(field, models.DateTimeField): value = timezone.localtime(value) 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) else: return smart_text(value)
def get_registrations_link(self, obj): icon = False approved_registrations_count = obj.approved_registrations.count() unapproved_registrations_count = obj.unapproved_registrations.count() if approved_registrations_count == 0: title = _( 'There are no approved registrations for this {}.').format( obj.subject_type.name_akuzativ) elif obj.min_registrations_count is not None and approved_registrations_count < obj.min_registrations_count: title = _('The number of approved registrations is lower than {}.' ).format(obj.min_registrations_count) elif obj.max_registrations_count is not None and approved_registrations_count > obj.max_registrations_count: title = _( 'The number of approved registrations is greater than {}.' ).format(obj.max_registrations_count) else: icon = True title = '' return format_html( '<a href="{url}" title="{title}">{icon} {approved}{unapproved}</a>', url=reverse('admin:{}_{}_changelist'.format( self.registration_model._meta.app_label, self.registration_model._meta.model_name, )) + '?subject__id__exact={}'.format(obj.id), title=title, icon=_boolean_icon(icon), approved=approved_registrations_count, unapproved=' + {}'.format(unapproved_registrations_count) if unapproved_registrations_count else '', ) + format_html( '<a class="popup-link" href="{url}" style="background-position: 0 0" title="{title}">' '<img src="{icon}" alt="+"/></a>', url=reverse('admin:{}_{}_add'.format( self.registration_model._meta.app_label, self.registration_model._meta.model_name, )) + '?subject={}'.format(obj.id), title=_('add registration'), icon=static('admin/img/icon-addlink.svg'), )
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = ( self.field["field"], self.form.instance, self.model_admin, ) try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if field in self.form.fields: widget = self.form[field].field.widget # This isn't elegant but suffices for contrib.auth's # ReadOnlyPasswordHashWidget. if getattr(widget, "read_only", False): return widget.render(field, value) if f is None: if getattr(attr, "boolean", False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) elif (isinstance(f.remote_field, (ForeignObjectRel, OneToOneField)) and value is not None): result_repr = self.get_admin_url(f.remote_field, value) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: if isinstance(f.rel, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def test_admin_views_competition(self): response = self.client.get(reverse("admin:main_album_changelist")) self.assertEqual(response.status_code, 200) self.assertContains( response, '<th scope="col" class="sortable column-artist__first_name">' '<div class="text"><a href="?o=3">Artist First Name</a></div>' '<div class="clear"></div>' '</th>', html=True, ) self.assertContains( response, '<td class="field-artist__full_name">Mark Knopfler</td>', html=True) self.assertContains(response, '<td class="field-artist__active">%s</td>' % _boolean_icon(True), html=True) self.assertContains(response, '<td class="field-artist__instrument">%s</td>' % dict(INSTRUMENTS_CHOICES)['VOICE'], html=True)
def get_html_is_into_offer(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon css_class = ' class = "repanier-a-info"' is_into_offer = self.is_into_offer switch_is_into_offer = reverse("is_into_offer", args=(self.id, )) javascript = """ (function($) {{ var lien = '{LINK}'; $.ajax({{ url: lien, cache: false, async: true, success: function (result) {{ $('#is_into_offer_{PRODUCT_ID}').html(result) }} }}); }})(django.jQuery); """.format(LINK=switch_is_into_offer, PRODUCT_ID=self.id) # return false; http://stackoverflow.com/questions/1601933/how-do-i-stop-a-web-page-from-scrolling-to-the-top-when-a-link-is-clicked-that-t link = '<div id="is_into_offer_{}"><a href="#" onclick="{};return false;"{}>{}</a></div>'.format( self.id, javascript, css_class, _boolean_icon(is_into_offer)) return mark_safe(link)
def display_for_field(value, field, empty_value_display): from django.contrib.admin.templatetags.admin_list import _boolean_icon if getattr(field, 'flatchoices', None): return dict(field.flatchoices).get(value, empty_value_display) # 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_value_display elif isinstance(field, models.DateTimeField): return formats.localize(timezone.template_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.IntegerField, models.FloatField)): return formats.number_format(value) elif isinstance(field, models.FileField) and value: return format_html('<a href="{}">{}</a>', value.url, value) else: return display_for_value(value, empty_value_display)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field[ 'field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): warnings.warn( "Deprecated allow_tags attribute used on %s. " "Use django.utils.html.format_html(), format_html_join(), " "or django.utils.safestring.mark_safe() instead." % attr, RemovedInDjango20Warning) result_repr = mark_safe(value) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main 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(timezone.template_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, models.FileField) and value: return format_html('<a href="{}">{}</a>', value.url, value) else: return smart_text(value)
def test_admin_views_competition(self): self.assertTrue(self.client.login(username='******', password='******')) response = self.client.get(reverse("admin:main_album_changelist")) self.assertEqual(response.status_code, 200) self.assertContains(response, '<td class="field-artist__full_name">Mark Knopfler</td>', html=True) self.assertContains(response, '<td class="field-artist__active">%s</td>' % _boolean_icon(True), html=True)
def get_booleanfield_value(self, field_name, value): return _boolean_icon(value)
def test_admin_views_list_select_related_competition(self): self.assertTrue(self.client.login(username='******', password='******')) response = self.client.get(reverse("admin:main_concert_changelist")) self.assertContains(response, '<td class="field-main_performer__is_on_tour">%s</td>' % _boolean_icon(True), html=True) self.assertEqual(response.status_code, 200)
def mptt_items_for_result(cl, result, form): first = True pk = cl.lookup_opts.pk.attname # figure out which field to indent mptt_indent_field = getattr(cl.model_admin, 'mptt_indent_field', None) if not mptt_indent_field: for field_name in cl.list_display: try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: if mptt_indent_field is None: attr = getattr(result, field_name, None) if callable(attr): # first callable field, use this if we can't find any model fields mptt_indent_field = field_name else: # first model field, use this one mptt_indent_field = field_name break for field_name in cl.list_display: row_class = '' f = None try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: # For non-field list_display values, the value is either a method, # property or returned via a callable. try: if callable(field_name): attr = field_name value = attr(result) elif hasattr(cl.model_admin, field_name) and \ not field_name == '__str__' and not field_name == '__unicode__': attr = getattr(cl.model_admin, field_name) value = attr(result) else: attr = getattr(result, field_name) if callable(attr): value = attr() else: value = attr allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: field_val = getattr(result, f.attname) if isinstance(f.rel, models.ManyToOneRel): if field_val is not None: result_repr = escape(getattr(result, f.name)) else: result_repr = EMPTY_CHANGELIST_VALUE # Dates and times are special: They're formatted in a certain way. elif isinstance(f, models.DateField) or isinstance(f, models.TimeField): if field_val: (date_format, datetime_format, time_format) = get_date_formats() if isinstance(f, models.DateTimeField): result_repr = capfirst(dateformat.format(field_val, datetime_format)) elif isinstance(f, models.TimeField): result_repr = capfirst(dateformat.time_format(field_val, time_format)) else: result_repr = capfirst(dateformat.format(field_val, date_format)) else: result_repr = EMPTY_CHANGELIST_VALUE row_class = ' class="nowrap"' # Booleans are special: We use images. elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField): result_repr = _boolean_icon(field_val) # DecimalFields are special: Zero-pad the decimals. elif isinstance(f, models.DecimalField): if field_val is not None: result_repr = ('%%.%sf' % f.decimal_places) % field_val else: result_repr = EMPTY_CHANGELIST_VALUE # Fields with choices are special: Use the representation # of the choice. elif f.flatchoices: result_repr = dict(f.flatchoices).get(field_val, EMPTY_CHANGELIST_VALUE) else: result_repr = escape(field_val) if force_unicode(result_repr) == '': result_repr = mark_safe(' ') if field_name == mptt_indent_field: level = getattr(result, result._mptt_meta.level_attr) padding_attr = ' style="padding-left:%spx"' % (5 + MPTT_ADMIN_LEVEL_INDENT * level) else: padding_attr = '' # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: table_tag = {True:'th', False:'td'}[first] first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] yield mark_safe(u'<%s%s%s><a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, padding_attr, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe(u'<td%s%s>%s</td>' % (row_class, padding_attr, result_repr)) if form: yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
def get_booleanfield_value(self, field_name, value): return _boolean_icon(value)
def _access(self, obj): if obj.access: return str(obj.access) + " " + _boolean_icon(obj.access_given) return ""
from __future__ import unicode_literals
def mptt_items_for_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname # #### MPTT ADDITION START # figure out which field to indent mptt_indent_field = getattr(cl.model_admin, 'mptt_indent_field', None) if not mptt_indent_field: for field_name in cl.list_display: try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: if (mptt_indent_field is None and field_name != 'action_checkbox'): mptt_indent_field = field_name else: # first model field, use this one mptt_indent_field = field_name break # #### MPTT ADDITION END # figure out how much to indent mptt_level_indent = getattr(cl.model_admin, 'mptt_level_indent', MPTT_ADMIN_LEVEL_INDENT) for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = get_empty_value_display(cl) else: if f is None: if field_name == 'action_checkbox': row_class = ' class="action-checkbox"' allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_text(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(result, f.name) if field_val is None: result_repr = get_empty_value_display(cl) else: result_repr = escape(field_val) else: result_repr = display_for_field(value, f) if isinstance(f, models.DateField)\ or isinstance(f, models.TimeField)\ or isinstance(f, models.ForeignKey): row_class = ' class="nowrap"' if force_text(result_repr) == '': result_repr = mark_safe(' ') # #### MPTT ADDITION START if field_name == mptt_indent_field: level = getattr(result, result._mptt_meta.level_attr) padding_attr = ' style="padding-%s:%spx"' % ( 'right' if get_language_bidi() else 'left', 5 + mptt_level_indent * level) else: padding_attr = '' # #### MPTT ADDITION END # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: table_tag = {True: 'th', False: 'td'}[first] first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_text(value))[1:-1] # #### MPTT SUBSTITUTION START yield mark_safe('<%s%s%s><a href="%s"%s>%s</a></%s>' % ( table_tag, row_class, padding_attr, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), # noqa conditional_escape(result_repr), table_tag)) # #### MPTT SUBSTITUTION END else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if (form and field_name in form.fields and not ( field_name == cl.model._meta.pk.name and form[cl.model._meta.pk.name].is_hidden)): bf = form[field_name] result_repr = mark_safe(force_text(bf.errors) + force_text(bf)) else: result_repr = conditional_escape(result_repr) # #### MPTT SUBSTITUTION START yield mark_safe('<td%s%s>%s</td>' % (row_class, padding_attr, result_repr)) # #### MPTT SUBSTITUTION END if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe('<td>%s</td>' % force_text(form[cl.model._meta.pk.name]))
def thumbnails_for_result(cl, result, form): """ Basically does the same thing as django's items_for_result, but makes all the items fit in one <td> element instead of separate elements for each field """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: # For non-field list_display values, the value is either a method, # property or returned via a callable. try: if callable(field_name): attr = field_name value = attr(result) elif hasattr(cl.model_admin, field_name) and \ not field_name == '__str__' and not field_name == '__unicode__': attr = getattr(cl.model_admin, field_name) value = attr(result) else: attr = getattr(result, field_name) if callable(attr): value = attr() else: value = attr allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: field_val = getattr(result, f.attname) if isinstance(f.rel, models.ManyToOneRel): if field_val is not None: result_repr = escape(getattr(result, f.name)) else: result_repr = EMPTY_CHANGELIST_VALUE # Dates and times are special: They're formatted in a certain way. elif isinstance(f, models.DateField) or isinstance(f, models.TimeField): if field_val: date_format = get_format('DATE_FORMAT') datetime_format = get_format('DATETIME_FORMAT') time_format = get_format('TIME_FORMAT') if isinstance(f, models.DateTimeField): result_repr = capfirst(dateformat.format(field_val, datetime_format)) elif isinstance(f, models.TimeField): result_repr = capfirst(dateformat.time_format(field_val, time_format)) else: result_repr = capfirst(dateformat.format(field_val, date_format)) else: result_repr = EMPTY_CHANGELIST_VALUE row_class = ' class="nowrap"' # Booleans are special: We use images. elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField): result_repr = _boolean_icon(field_val) # DecimalFields are special: Zero-pad the decimals. elif isinstance(f, models.DecimalField): if field_val is not None: result_repr = ('%%.%sf' % f.decimal_places) % field_val else: result_repr = EMPTY_CHANGELIST_VALUE # Fields with choices are special: Use the representation # of the choice. elif f.flatchoices: result_repr = dict(f.flatchoices).get(field_val, EMPTY_CHANGELIST_VALUE) else: result_repr = escape(field_val) if force_unicode(result_repr) == '': result_repr = mark_safe(' ') # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: table_tag = {True:'th', False:'td'}[first] first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] if cl.is_popup and cl.params['pop'] == u'2': yield mark_safe(u'<a href="%s"%s>%s</a>' % \ ('#', (cl.is_popup and ' onclick="FileBrowserDialogue.fileSubmit(\'%s\', \'%s\', \'%s\'); return false;"' % (result.media_url or '', quo_esc(result.caption) or '', result.get_absolute_url())), conditional_escape(result_repr))) #(url, (cl.is_popup and ' onclick="FileBrowserDialogue.fileSubmit(\'%s\'); return false;"' % result.get_absolute_url() or ''), conditional_escape(result_repr))) else: yield mark_safe(u'<a href="%s"%s>%s</a>' % \ (url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr))) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe(u'%s' % (result_repr)) if form: yield mark_safe(force_unicode(form[cl.model._meta.pk.name]))
def mptt_items_for_result(cl, result, form): first = True pk = cl.lookup_opts.pk.attname # figure out which field to indent mptt_indent_field = None for field_name in cl.list_display: try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: if mptt_indent_field is None: attr = getattr(result, field_name, None) if callable(attr): # first callable field, use this if we can't find any model fields mptt_indent_field = field_name else: # first model field, use this one mptt_indent_field = field_name break for field_name in cl.list_display: row_class = '' f = None try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: # For non-field list_display values, the value is either a method, # property or returned via a callable. try: if callable(field_name): attr = field_name value = attr(result) elif hasattr(cl.model_admin, field_name) and \ not field_name == '__str__' and not field_name == '__unicode__': attr = getattr(cl.model_admin, field_name) value = attr(result) else: attr = getattr(result, field_name) if callable(attr): value = attr() else: value = attr allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: field_val = getattr(result, f.attname) if isinstance(f.rel, models.ManyToOneRel): if field_val is not None: result_repr = escape(getattr(result, f.name)) else: result_repr = EMPTY_CHANGELIST_VALUE # Dates and times are special: They're formatted in a certain way. elif isinstance(f, models.DateField) or isinstance( f, models.TimeField): if field_val: (date_format, datetime_format, time_format) = get_date_formats() if isinstance(f, models.DateTimeField): result_repr = capfirst( dateformat.format(field_val, datetime_format)) elif isinstance(f, models.TimeField): result_repr = capfirst( dateformat.time_format(field_val, time_format)) else: result_repr = capfirst( dateformat.format(field_val, date_format)) else: result_repr = EMPTY_CHANGELIST_VALUE row_class = ' class="nowrap"' # Booleans are special: We use images. elif isinstance(f, models.BooleanField) or isinstance( f, models.NullBooleanField): result_repr = _boolean_icon(field_val) # DecimalFields are special: Zero-pad the decimals. elif isinstance(f, models.DecimalField): if field_val is not None: result_repr = ('%%.%sf' % f.decimal_places) % field_val else: result_repr = EMPTY_CHANGELIST_VALUE # Fields with choices are special: Use the representation # of the choice. elif f.flatchoices: result_repr = dict(f.flatchoices).get(field_val, EMPTY_CHANGELIST_VALUE) else: result_repr = escape(field_val) if force_unicode(result_repr) == '': result_repr = mark_safe(' ') if field_name == mptt_indent_field: level = getattr(result, result._mptt_meta.level_attr) padding_attr = ' style="padding-left:%spx"' % ( 5 + MPTT_ADMIN_LEVEL_INDENT * level) else: padding_attr = '' # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links ) or field_name in cl.list_display_links: table_tag = {True: 'th', False: 'td'}[first] first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] yield mark_safe(u'<%s%s%s><a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, padding_attr, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe( force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe(u'<td%s%s>%s</td>' % (row_class, padding_attr, result_repr)) if form: yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
def items_for_result(cl, result, form): """ Generates the actual list of data. @jjdelc: This has been shamelessly copied from original django.contrib.admin.templatetags.admin_list.items_for_result in order to alter the dispay for the first element """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE if isinstance(f.rel, models.ManyToOneRel): result_repr = escape(getattr(result, f.name)) else: result_repr = display_for_field(value, f) if isinstance(f, models.DateField) or isinstance( f, models.TimeField): row_class = ' class="nowrap"' if force_unicode(result_repr) == '': result_repr = mark_safe(' ') # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links ) or field_name in cl.list_display_links: table_tag = {True: 'th', False: 'td'}[first] # This spacer indents the nodes based on their depth spacer = '<span class="spacer"> </span>' * ( result.get_depth() - 1) if first else '' # This shows a collapse or expand link for nodes with childs collapse = '<a href="#" title="" class="collapse expanded">-</a>' if result.get_children_count( ) > 0 else '<span class="collapse"> </span>' # Add a <td/> before the first col to show the drag handler drag_handler = '' if first: drag_handler = '<td class="drag-handler"><span> </span></td>' first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] yield mark_safe(u'%s<%s%s>%s %s <a href="%s"%s>%s</a></%s>' % \ (drag_handler, table_tag, row_class, spacer, collapse, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe( force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr)) if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
def mptt_items_for_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname ##### MPTT ADDITION START # figure out which field to indent mptt_indent_field = getattr(cl.model_admin, 'mptt_indent_field', None) if not mptt_indent_field: for field_name in cl.list_display: try: f = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: if mptt_indent_field is None: attr = getattr(result, field_name, None) if callable(attr): # first callable field, use this if we can't find any model fields mptt_indent_field = field_name else: # first model field, use this one mptt_indent_field = field_name break ##### MPTT ADDITION END # figure out how much to indent mptt_level_indent = getattr(cl.model_admin, 'mptt_level_indent', MPTT_ADMIN_LEVEL_INDENT) for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: if field_name == u'action_checkbox': row_class = ' class="action-checkbox"' allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(result, f.name) if field_val is None: result_repr = EMPTY_CHANGELIST_VALUE else: result_repr = escape(field_val) else: result_repr = display_for_field(value, f) if isinstance(f, models.DateField)\ or isinstance(f, models.TimeField)\ or isinstance(f, models.ForeignKey): row_class = ' class="nowrap"' if force_unicode(result_repr) == '': result_repr = mark_safe(' ') ##### MPTT ADDITION START if field_name == mptt_indent_field: level = getattr(result, result._mptt_meta.level_attr) padding_attr = ' style="padding-left:%spx"' % ( 5 + mptt_level_indent * level) else: padding_attr = '' ##### MPTT ADDITION END # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links ) or field_name in cl.list_display_links: table_tag = {True: 'th', False: 'td'}[first] first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] ##### MPTT SUBSTITUTION START yield mark_safe(u'<%s%s%s><a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, padding_attr, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) ##### MPTT SUBSTITUTION END else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if (form and field_name in form.fields and not (field_name == cl.model._meta.pk.name and form[cl.model._meta.pk.name].is_hidden)): bf = form[field_name] result_repr = mark_safe( force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) ##### MPTT SUBSTITUTION START yield mark_safe(u'<td%s%s>%s</td>' % (row_class, padding_attr, result_repr)) ##### MPTT SUBSTITUTION END if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
}) def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field[ 'field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist), e: result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE elif isinstance(f.rel, ManyToManyRel): result_repr = ", ".join(map(unicode, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr) class InlineAdminFormSet(object):
def items_for_tree_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = get_empty_value_display(cl) else: if f is None: if django.VERSION[1] == 4: if field_name == 'action_checkbox': row_class = ' class="action-checkbox disclosure"' allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_text(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if value is None: result_repr = get_empty_value_display(cl) if isinstance(f.rel, models.ManyToOneRel): result_repr = escape(getattr(result, f.name)) else: result_repr = display_for_field(value, f, '') if isinstance(f, models.DateField) or isinstance(f, models.TimeField): row_class = ' class="nowrap"' if first: if django.VERSION[1] < 4: try: f, attr, checkbox_value = lookup_field('action_checkbox', result, cl.model_admin) if row_class: row_class = "%s%s" % (row_class[:-1], ' disclosure"') else: row_class = ' class="disclosure"' except (AttributeError, ObjectDoesNotExist): pass if force_text(result_repr) == '': result_repr = mark_safe(' ') # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: if django.VERSION[1] < 4: table_tag = 'td' # {True:'th', False:'td'}[first] else: table_tag = {True: 'th', False: 'td'}[first] url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_text(value))[1:] first = False if django.VERSION[1] < 4: # versions 1.3 and smaller yield mark_safe( '<%s%s>%s<a href="%s"%s>%s</a></%s>' % (table_tag, row_class, checkbox_value, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) elif django.VERSION[1] < 7: # versions 1.4 to 1.7 yield mark_safe( '<%s%s><a href="%s"%s>%s</a></%s>' % (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # versions 1.8 and greater result_id = escapejs(value) yield mark_safe( format_html( '<{}{}><a href="{}"{}>{}</a></{}>', table_tag, row_class, url, format_html( ' onclick="opener.dismissRelatedLookupPopup(window, ' ''{}'); return false;"', result_id ) if cl.is_popup else '', result_repr, table_tag) ) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe(force_text(bf.errors) + force_text(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe('<td%s>%s</td>' % (row_class, result_repr)) if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe('<td>%s</td>' % force_text(form[cl.model._meta.pk.name]))
def branch_closed_live(self, branch): return _boolean_icon(branch.inforequest.closed) if branch else u'--'
def is_api_key_set(self, obj: "HealthcareProvince"): if obj.api_key is None: return _boolean_icon(False) return _boolean_icon(True)
def metadata_check(self, node): icon = _boolean_icon(node.has_metadata_including_descendants()) return '<span class="metadata"><span class="metadata-icon">%s</span><span class="displayed-metadata">%s</span></span>' % ( icon, node.get_caption_formatted())
def get_html_is_into_offer(self, contract=None, contract_content=None): from django.contrib.admin.templatetags.admin_list import _boolean_icon css_class = ' class = "btn"' if contract is not None or contract_content is not None: css_class = EMPTY_STRING if contract_content is None: contract_content = ContractContent.objects.filter( product=self, contract=contract).order_by('?').first() if contract_content is not None and contract_content.permanences_dates is not None: all_dates_str = sorted( list( filter( None, contract_content.permanences_dates.split( settings.DJANGO_SETTINGS_DATES_SEPARATOR)))) is_into_offer = len(all_dates_str) > 0 flexible_dates = contract_content.flexible_dates else: all_dates_str = [] is_into_offer = False flexible_dates = False if contract.permanences_dates is not None: contract_all_dates_str = sorted( list( filter( None, contract.permanences_dates.split( settings.DJANGO_SETTINGS_DATES_SEPARATOR)))) else: contract_all_dates_str = [] contract_dates_array = [] month_save = None selected_dates_counter = 0 for one_date_str in contract_all_dates_str: one_date = parse_date(one_date_str) if month_save != one_date.month: month_save = one_date.month new_line = "<br>" else: new_line = EMPTY_STRING # Important : linked to django.utils.dateparse.parse_date format switch_is_into_offer = reverse('is_into_offer_content', args=(self.id, contract.id, one_date_str)) javascript = """ (function($) {{ var lien = '{LINK}'; $.ajax({{ url: lien, cache: false, async: true, success: function (result) {{ $('#is_into_offer_{PRODUCT_ID}').html(result) }} }}); }})(django.jQuery); """.format(LINK=switch_is_into_offer, PRODUCT_ID=self.id) if one_date_str in all_dates_str: color = "green" icon = " {}".format(_boolean_icon(True)) selected_dates_counter += 1 else: color = "red" icon = " {}".format(_boolean_icon(False)) link = """ {}<a href="#" onclick="{};return false;" style="color:{} !important;">{}{}</a> """.format( new_line, javascript, color, icon, one_date.strftime(settings.DJANGO_SETTINGS_DAY_MONTH)) contract_dates_array.append(link) contract_dates = ", ".join(contract_dates_array) if selected_dates_counter > 1: switch_flexible_dates = reverse('flexible_dates', args=(self.id, contract.id)) javascript = """ (function($) {{ var lien = '{LINK}'; $.ajax({{ url: lien, cache: false, async: true, success: function (result) {{ $('#is_into_offer_{PRODUCT_ID}').html(result) }} }}); }})(django.jQuery); """.format(LINK=switch_flexible_dates, PRODUCT_ID=self.id) if flexible_dates: color = EMPTY_STRING flexible_dates_display = " {}".format(_("Flexible dates")) else: color = EMPTY_STRING flexible_dates_display = " {} {}".format( selected_dates_counter, _("Fixed dates")) flexible_dates_link = """ <a href="#" onclick="{};return false;" style="color:{} !important;">{}</a> """.format( javascript, color, flexible_dates_display, ) else: flexible_dates_link = EMPTY_STRING else: is_into_offer = self.is_into_offer contract_dates = EMPTY_STRING flexible_dates_link = EMPTY_STRING switch_is_into_offer = reverse( 'is_into_offer', args=(self.id, contract.id if contract is not None else 0)) javascript = """ (function($) {{ var lien = '{LINK}'; $.ajax({{ url: lien, cache: false, async: true, success: function (result) {{ $('#is_into_offer_{PRODUCT_ID}').html(result) }} }}); }})(django.jQuery); """.format(LINK=switch_is_into_offer, PRODUCT_ID=self.id) # return false; http://stackoverflow.com/questions/1601933/how-do-i-stop-a-web-page-from-scrolling-to-the-top-when-a-link-is-clicked-that-t link = "<div id=\"is_into_offer_{}\"><a href=\"#\" onclick=\"{};return false;\"{}>{}</a>{}{}</div>".format( self.id, javascript, css_class, _boolean_icon(is_into_offer), flexible_dates_link, contract_dates) return mark_safe(link)
def metadata_check(self, node): icon = _boolean_icon(node.has_metadata_including_descendants()) return '<span class="metadata"><span class="metadata-icon">%s</span><span class="displayed-metadata">%s</span></span>' % ( icon, node.get_caption_formatted())
def registration_allowed_icon(self, obj): return _boolean_icon(obj.registration_allowed)
def boolean_icon(item): return _boolean_icon(item)
from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.db import transaction import mock def print_response(response, stdout=False, filename="response.html"): content = response.content.decode() if stdout: print(content) else: with open(filename, "w") as f: # pragma: no cover f.write(content) # pragma: no cover ICON_FALSE = _boolean_icon(False) ICON_UNKNOWN = _boolean_icon(None) class RunCommitHooksMixin(object): def run_commit_hooks(self): """ Fake transaction commit to run delayed on_commit functions :return: """ for db_name in reversed(self._databases_names()): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.validate_no_atomic_block", lambda a: False, ): transaction.get_connection(using=db_name).run_and_clear_commit_hooks()
def boolean_icon(field_val): return _boolean_icon(field_val)
def items_for_tree_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = get_empty_value_display(cl) else: if f is None: if django.VERSION[1] == 4: if field_name == 'action_checkbox': row_class = ' class="action-checkbox disclosure"' allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_text(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if value is None: result_repr = get_empty_value_display(cl) if isinstance(f.rel, models.ManyToOneRel): result_repr = escape(getattr(result, f.name)) else: result_repr = display_for_field(value, f, '') if isinstance(f, models.DateField) or isinstance(f, models.TimeField): row_class = ' class="nowrap"' if first: if django.VERSION[1] < 4: try: f, attr, checkbox_value = lookup_field('action_checkbox', result, cl.model_admin) if row_class: row_class = "%s%s" % (row_class[:-1], ' disclosure"') else: row_class = ' class="disclosure"' except (AttributeError, ObjectDoesNotExist): pass if force_text(result_repr) == '': result_repr = mark_safe(' ') # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: if django.VERSION[1] < 4: table_tag = 'td' # {True:'th', False:'td'}[first] else: table_tag = {True: 'th', False: 'td'}[first] url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_text(value))[1:] first = False if django.VERSION[1] < 4: yield mark_safe( '<%s%s>%s<a href="%s"%s>%s</a></%s>' % (table_tag, row_class, checkbox_value, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: yield mark_safe( '<%s%s><a href="%s"%s>%s</a></%s>' % (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe(force_text(bf.errors) + force_text(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe('<td%s>%s</td>' % (row_class, result_repr)) if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe('<td>%s</td>' % force_text(form[cl.model._meta.pk.name]))