예제 #1
0
 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:
                     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)
             result_repr = linebreaksbr(result_repr)
     return conditional_escape(result_repr)
예제 #2
0
def field_contents_foreign_linked(admin_field):
    """Return the .contents attribute of the admin_field, and if it
    is a foreign key, wrap it in a link to the admin page for that
    object.

    Use by replacing '{{ field.contents }}' in an admin template (e.g.
    fieldset.html) with '{{ field|field_contents_foreign_linked }}'.
    """
    fieldname = admin_field.field['field']
    displayed = admin_field.contents()
    obj = admin_field.form.instance

    if not hasattr(admin_field.model_admin,
                   'linked_readonly_fields') or fieldname not in admin_field \
            .model_admin \
            .linked_readonly_fields:
        return displayed

    try:
        fieldtype, attr, value = lookup_field(fieldname, obj,
                                              admin_field.model_admin)
    except ObjectDoesNotExist:
        fieldtype = None

    if isinstance(fieldtype, ForeignKey):
        try:
            url = admin_url(value)
        except NoReverseMatch:
            url = None
        if url:
            displayed = "<a href='%s'>%s</a>" % (url, displayed)
    return mark_safe(displayed)
예제 #3
0
 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:
                     result_repr = linebreaksbr(result_repr)
         else:
             if isinstance(getattr(f, 'rel', None), ManyToManyRel) and value is not None:
                 result_repr = ", ".join(map(six.text_type, value.all()))
             else:
                 result_repr = display_for_field(value, f)
             result_repr = linebreaksbr(result_repr)
     return conditional_escape(result_repr)
예제 #4
0
 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 = force_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)
예제 #5
0
파일: options.py 프로젝트: mrmuxl/keops
    def db_list(self, request):
        list_display = self.get_list_display(request)
        list_display_links = self.get_list_display_links(request, list_display)
        list_filter = self.get_list_filter(request)
        search_fields = self.get_search_fields(request)

        ChangeList = self.get_changelist(request)
        cl = ChangeList(request, self.model, list_display,
            list_display_links, list_filter, self.date_hierarchy,
            search_fields, self.list_select_related, self.list_per_page,
            self.list_max_show_all, self.list_editable, self)
        q = cl.get_queryset(request)
        r = []
        for obj in q:
            row = {'pk': obj.pk}
            for field_name in cl.list_display:
                try:
                    f, attr, value = lookup_field(field_name, obj, cl.model_admin)
                except ObjectDoesNotExist:
                    result_repr = EMPTY_CHANGELIST_VALUE
                    row[field_name] = result_repr
                else:
                    row[field_name] = value
            r.append(row)
        return JsonResponse({'items': r})
예제 #6
0
def items_for_result(view, result, request):
    """
    Generates the actual list of data.
    """
    modeladmin = view.model_admin
    for field_name in view.list_display:
        empty_value_display = modeladmin.get_empty_value_display(field_name)
        row_classes = ['field-%s' % field_name, 'title']
        try:
            f, attr, value = lookup_field(field_name, result, modeladmin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display',
                                          empty_value_display)
            if f is None or f.auto_created:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean or not value:
                    allow_tags = True
                result_repr = display_for_value(value, empty_value_display,
                                                boolean)

                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                if isinstance(f, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f,
                                                    empty_value_display)

                if isinstance(
                        f,
                    (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_str(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_classes.extend(
            modeladmin.get_extra_class_names_for_field_col(result, field_name))
        row_attrs = modeladmin.get_extra_attrs_for_field_col(
            result, field_name)
        row_attrs['class'] = ' '.join(row_classes)
        row_attrs_flat = flatatt(row_attrs)
        if field_name == modeladmin.get_list_display_add_buttons(request):
            edit_url = view.url_helper.get_action_url('edit', result.pk)
            yield format_html(
                '<td{}><div class="title-wrapper"><a href="{}" title="{}">{}</a></div></td>',
                row_attrs_flat, edit_url,
                _('Edit this %s') % view.verbose_name, result_repr)
        else:
            yield format_html('<td{}>{}</td>', row_attrs_flat, result_repr)
예제 #7
0
def items_for_result(cl, result, form, template, request):
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        empty_value_display = cl.model_admin.get_empty_value_display()
        row_class = ''
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except (AttributeError, ObjectDoesNotExist):
            result_repr = empty_value_display
        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_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 = empty_value_display
                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_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')

        if field_name in cl.list_display_links:
            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:]
            yield render_template(result, template, request, cl)
        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)
    if form:
        yield mark_safe(force_text(form[cl.model._meta.pk.name]))
예제 #8
0
    def get_results(self):
        paginator = Paginator(self.order_queryset, self.num_per_page)

        if SEARCH_PAGE_VAR in self.params and self.params[SEARCH_PAGE_VAR] is not None:
            try:
                page = int(self.params[SEARCH_PAGE_VAR])
            except:
                page = int(self.params[PAGE_VAR])
        else:
            page = int(self.params[PAGE_VAR])

        try:
            results = paginator.page(page)
        except PageNotAnInteger:
            results = paginator.page(1)
        except EmptyPage:
            results = paginator.page(paginator.num_pages)

        object_list = []
        for instance in results:
            list_one = []
            for field in self.model._meta.fields:
                f, attr, value = lookup_field(field.name, instance)
                list_one.append(value)
            object_list.append(list_one)

        results.object_list = object_list

        return results
예제 #9
0
파일: helpers.py 프로젝트: GeyseR/django
 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)
예제 #10
0
def contents_or_fk_link(field):
    """
    Return field contents or link to related object if foreign key field

    Example Usage::

        {% load relatives %}
        {{ field|contents_or_fk_link }}
    """
    contents = field.contents()
    field_name = field.field['field']
    obj = field.form.instance
    if not isinstance(field_name, str):
        return contents
    try:
        related_obj = getattr(obj, field_name)
    except (AttributeError, ObjectDoesNotExist):
        return contents
    else:
        model_field, _, _ = lookup_field(field_name, obj, field.model_admin)
        if ((model_field is None or model_field.remote_field)
                and hasattr(related_obj, '_meta')):
            try:
                return mark_safe('<a href="%s">%s</a>' %
                                 (get_admin_url(related_obj), contents))
            except NoReverseMatch:
                pass
        return contents
예제 #11
0
파일: admin.py 프로젝트: oaubert/michaux
def export_model_as_csv(modeladmin, request, queryset):
    if hasattr(modeladmin, 'exportable_fields'):
        field_list = modeladmin.exportable_fields
    else:
        # Copy modeladmin.list_display to remove action_checkbox
        field_list = list(modeladmin.list_display)

    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s-%s-export-%s.csv' % (
        __package__.lower(),
        queryset.model.__name__.lower(),
        datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'),
    )

    writer = csv.writer(response)
    writer.writerow(
        [admin_util.label_for_field(f, queryset.model, modeladmin) for f in field_list],
    )

    for obj in queryset:
        csv_line_values = []
        for field in field_list:
            field_obj, attr, value = admin_util.lookup_field(field, obj, modeladmin)
            csv_line_values.append(value)

        writer.writerow(csv_line_values)

    return response
예제 #12
0
def items_for_result(cl, item):
    results = []

    for field_index, field_name in enumerate(cl.list_display):
        if field_name == 'action_checkbox':
            continue

        empty_value_display = cl.model_admin.get_empty_value_display()

        try:
            f, attr, value = lookup_field(field_name, item, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display',
                                          empty_value_display)
            if f is None or f.auto_created:
                boolean = getattr(attr, 'boolean', False)
                result_repr = display_for_value(value, empty_value_display,
                                                boolean)
            else:
                if isinstance(f.remote_field, models.ManyToOneRel):
                    field_val = getattr(item, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f,
                                                    empty_value_display)

        results.append(result_repr)

    return results
예제 #13
0
    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)
예제 #14
0
def export_as_xls(modeladmin, request, queryset):
    """
    Generic xls export admin action.
    """
    fields = []

    # PUT THE LIST OF FIELD NAMES YOU DON'T WANT TO EXPORT
    exclude_fields = []

    # foreign key related fields
    extras = ['']

    if not request.user.is_staff:
        raise PermissionDenied

    for f in modeladmin.list_display:
        if f not in exclude_fields:
            fields.append(f)
    fields.extend(extras)

    opts = modeladmin.model._meta

    wb = Workbook()
    ws0 = wb.add_sheet('0')
    col = 0
    field_names = []

    # write header row
    for field in fields:
        ws0.write(0, col, field)
        field_names.append(field)
        col = col + 1
    row = 1

    # Write data rows
    for obj in queryset:
        col = 0
        for field in field_names:
            if field in extras:
                try:
                    val = [eval('obj.' + field)
                           ]  # eval sucks but easiest way to deal
                except:
                    val = ['None']
            else:
                try:
                    val = lookup_field(field, obj, modeladmin)
                except:
                    val = ['None']
            ws0.write(row, col, str(strip_tags(val[-1])).strip())
            col = col + 1

        row = row + 1

    wb.save('/tmp/output.xls')
    response = HttpResponse(open('/tmp/output.xls', 'r').read(),
                            mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s.xls' % unicode(
        opts).replace('.', '_')
    return response
예제 #15
0
def export_model_as_csv(modeladmin, request, queryset):
    if hasattr(modeladmin, 'exportable_fields'):
        field_list = modeladmin.exportable_fields
    else:
        # Copy modeladmin.list_display to remove action_checkbox
        field_list = list(modeladmin.list_display[:])
        if 'action_checkbox' in field_list:
            field_list.remove('action_checkbox')

    response = HttpResponse(content_type='text/csv')
    response[
        'Content-Disposition'] = 'attachment; filename=%s-%s-export_%s.csv' % (
            __package__.lower(),
            queryset.model.__name__.lower(),
            datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
        )

    writer = csv.writer(response)
    writer.writerow([
        admin_util.label_for_field(f, queryset.model, modeladmin)
        for f in field_list
    ], )

    for obj in queryset:
        csv_line_values = []
        for field in field_list:
            field_obj, attr, value = admin_util.lookup_field(
                field, obj, modeladmin)
            csv_line_values.append(value)

        writer.writerow(csv_line_values)

    return response
예제 #16
0
def djmoney_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_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(str, value.all()))
            else:
                result_repr = smart_unicode(value)
    return conditional_escape(result_repr)
예제 #17
0
def export_queryset_as_csv(modeladmin, request, queryset):

    if hasattr(modeladmin, 'export_fields'):
        field_list = modeladmin.export_fields
    else:
        # Copy modeladmin.list_display to remove action_checkbox
        field_list = modeladmin.list_display[:]
        field_list.remove('action_checkbox')

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="cm_data.csv"'

    writer = csv.writer(response)
    writer.writerow([
        utils.label_for_field(f, queryset.model, modeladmin).encode('utf-8') for f in field_list
    ])

    for obj in queryset:
        csv_line_values = []
        csv_line_tmp = []
        for field in field_list:
            field_obj, attr, value = utils.lookup_field(field, obj, modeladmin)
            if isinstance(value, unicode) :
                csv_line_values.append(value.encode('utf-8'))
            else:
                csv_line_values.append(value)
        writer.writerow(csv_line_values)

    return response
예제 #18
0
파일: suit_tags.py 프로젝트: eteks/Adjod
def field_contents_foreign_linked(admin_field):
    """Return the .contents attribute of the admin_field, and if it
    is a foreign key, wrap it in a link to the admin page for that
    object.

    Use by replacing '{{ field.contents }}' in an admin template (e.g.
    fieldset.html) with '{{ field|field_contents_foreign_linked }}'.
    """
    fieldname = admin_field.field['field']
    displayed = admin_field.contents()
    obj = admin_field.form.instance

    if not hasattr(admin_field.model_admin,
                   'linked_readonly_fields') or fieldname not in admin_field \
        .model_admin \
        .linked_readonly_fields:
        return displayed

    try:
        fieldtype, attr, value = lookup_field(fieldname, obj,
                                              admin_field.model_admin)
    except ObjectDoesNotExist:
        fieldtype = None

    if isinstance(fieldtype, ForeignKey):
        try:
            url = admin_url(value)
        except NoReverseMatch:
            url = None
        if url:
            displayed = "<a href='%s'>%s</a>" % (url, displayed)
    return mark_safe(displayed)
예제 #19
0
def contents_or_fk_link(field):
    """
    Return field contents or link to related object if foreign key field

    Example Usage::

        {% load relatives %}
        {{ field|contents_or_fk_link }}
    """
    contents = field.contents()
    field_name = field.field['field']
    obj = field.form.instance
    if not isinstance(field_name, str):
        return contents
    try:
        related_obj = getattr(obj, field_name)
    except ObjectDoesNotExist:
        return contents
    else:
        model_field, _, _ = lookup_field(field_name, obj, field.model_admin)
        if model_field.remote_field and hasattr(related_obj, '_meta'):
            try:
                return mark_safe('<a href="%s">%s</a>' %
                                 (get_admin_url(related_obj), contents))
            except NoReverseMatch:
                pass
        return contents
예제 #20
0
 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)
예제 #21
0
 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)
예제 #22
0
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)
예제 #23
0
    def export_as_csv(modeladmin, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response[
            'Content-Disposition'] = 'attachment; filename=%s.csv' % modeladmin.opts.db_table

        writer = csv.writer(response)
        if header:
            fields_header = []
            for field_name in fields:
                text, attr = label_for_field(field_name,
                                             modeladmin.model,
                                             model_admin=modeladmin,
                                             return_attr=True)
                fields_header.append(text.capitalize())
            writer.writerow(fields_header)

        for obj in queryset:
            line = []
            for field_name in fields:
                f, attr, value = lookup_field(field_name, obj, modeladmin)
                if f is None or f.auto_created:
                    boolean = getattr(attr, 'boolean', False)
                    result_repr = display_for_value(value, boolean)
                else:
                    if isinstance(f.rel, models.ManyToOneRel):
                        field_val = getattr(obj, f.name)
                        if field_val is None:
                            result_repr = '-'
                        else:
                            result_repr = field_val
                    else:
                        result_repr = display_for_field(value, f, '-')
                line.append(strip_tags(u'%s' % result_repr))
            writer.writerow(line)
        return response
예제 #24
0
 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)
예제 #25
0
def items_for_result(view, result):
    """
    Generates the actual list of data.
    """
    modeladmin = view.model_admin
    for field_name in view.list_display:
        empty_value_display = modeladmin.get_empty_value_display(field_name)
        row_classes = ['field-%s' % field_name]
        try:
            f, attr, value = lookup_field(field_name, result, modeladmin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display',
                                          empty_value_display)
            if f is None or f.auto_created:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean or not value:
                    allow_tags = True
                if django.VERSION >= (1, 9):
                    result_repr = display_for_value(value, empty_value_display,
                                                    boolean)
                else:
                    result_repr = display_for_value(value, boolean)

                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                if isinstance(f, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    if django.VERSION >= (1, 9):
                        result_repr = display_for_field(
                            value, f, empty_value_display)
                    else:
                        result_repr = display_for_field(value, f)

                if isinstance(
                        f,
                    (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_classes.extend(
            modeladmin.get_extra_class_names_for_field_col(result, field_name))
        row_attrs = modeladmin.get_extra_attrs_for_field_col(
            result, field_name)
        row_attrs['class'] = ' '.join(row_classes)
        row_attrs_flat = flatatt(row_attrs)
        yield format_html('<td{}>{}</td>', row_attrs_flat, result_repr)
예제 #26
0
def items_for_result(view, result):
    """
    Generates the actual list of data.
    """
    modeladmin = view.model_admin
    for field_name in view.list_display:
        empty_value_display = modeladmin.get_empty_value_display(field_name)
        row_classes = ['field-%s' % field_name]
        try:
            f, attr, value = lookup_field(field_name, result, modeladmin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(
                attr, 'empty_value_display', empty_value_display)
            if f is None or f.auto_created:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean or not value:
                    allow_tags = True
                if django.VERSION >= (1, 9):
                    result_repr = display_for_value(
                        value, empty_value_display, boolean)
                else:
                    result_repr = display_for_value(value, boolean)

                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                if isinstance(f, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    if django.VERSION >= (1, 9):
                        result_repr = display_for_field(
                            value, f, empty_value_display)
                    else:
                        result_repr = display_for_field(value, f)

                if isinstance(f, (
                    models.DateField, models.TimeField, models.ForeignKey)
                ):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_classes.extend(
            modeladmin.get_extra_class_names_for_field_col(result, field_name)
        )
        row_attrs = modeladmin.get_extra_attrs_for_field_col(result, field_name)
        row_attrs['class'] = ' ' . join(row_classes)
        row_attrs_flat = flatatt(row_attrs)
        yield format_html('<td{}>{}</td>', row_attrs_flat, result_repr)
예제 #27
0
    def to_row_dict(self, item):
        """ Returns an OrderedDict (in the order given by list_export) of the exportable information for a model instance"""
        row_dict = OrderedDict()
        for field in self.list_export:
            f, attr, value = lookup_field(field, item, self.model_admin)
            if not value:
                value = getattr(attr, 'empty_value_display', self.model_admin.get_empty_value_display(field))
            row_dict[field] = value

        return row_dict
예제 #28
0
def get_result_and_row_class(cl, field_name, result):
    if django.VERSION >= (1, 9):
        empty_value_display = cl.model_admin.get_empty_value_display()
    else:
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        empty_value_display = EMPTY_CHANGELIST_VALUE
    row_classes = ['field-%s' % field_name]
    try:
        f, attr, value = lookup_field(field_name, result, cl.model_admin)
    except ObjectDoesNotExist:
        result_repr = empty_value_display
    else:
        if django.VERSION >= (1, 9):
            empty_value_display = getattr(attr, 'empty_value_display',
                                          empty_value_display)
        if f is None:
            if field_name == 'action_checkbox':
                row_classes = ['action-checkbox']
            allow_tags = getattr(attr, 'allow_tags', False)
            boolean = getattr(attr, 'boolean', False)
            if django.VERSION >= (1, 9):
                result_repr = display_for_value(value, empty_value_display,
                                                boolean)
            else:
                result_repr = display_for_value(value, boolean)
            # Strip HTML tags in the resulting text, except if the
            # function has an "allow_tags" attribute set to True.
            # WARNING: this will be deprecated in Django 2.0
            if allow_tags:
                result_repr = mark_safe(result_repr)
            if isinstance(value, (datetime.date, datetime.time)):
                row_classes.append('nowrap')
        else:
            related_field_name = 'rel' if django.VERSION <= (
                2, 0) else 'remote_field'
            if isinstance(getattr(f, related_field_name), models.ManyToOneRel):
                field_val = getattr(result, f.name)
                if field_val is None:
                    result_repr = empty_value_display
                else:
                    result_repr = field_val
            else:
                if django.VERSION >= (1, 9):
                    result_repr = display_for_field(value, f,
                                                    empty_value_display)
                else:
                    result_repr = display_for_field(value, f)
            if isinstance(
                    f,
                (models.DateField, models.TimeField, models.ForeignKey)):
                row_classes.append('nowrap')
        if force_str(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
    row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
    return result_repr, row_class
예제 #29
0
def export_as_xls(modeladmin, request, queryset):
    ##    if queryset.count()>settings.EXPORT_RECORDS_LIMIT:
    ##        messages.error(request,"No se pueden exp:ortar %s registros todos juntos"% str(settings.EXPORT_RECORDS_LIMIT))
    fields = []
    exclude_fields = []
    #foreign key related fieds
    extras = ['']

    if not request.user.is_staff:
        raise PermissionDenied

    for f in modeladmin.list_display:
        if f not in exclude_fields:
            fields.append(f)
    fields.extend(extras)

    opts = modeladmin.model._meta
    wb = Workbook()
    ws0 = wb.add_sheet('ss')
    col = 0
    field_names = []

    #escribe la fila cabecera.
    for field in fields:
        ws0.write(0, col, field)
        field_names.append(field)
        col = col + 1
    row = 1

    #escribe la data de columans
    for obj in queryset:
        col = 0
        for field in field_names:
            if field in extras:
                try:
                    val = [eval('obj.' + field)]
                except:
                    val = ['None']
            else:
                try:
                    val = lookup_field(field, obj, modeladmin)
                except:
                    print "aca nno pudo con este campo.."
                    val = ['None']
            ws0.write(row, col, str((val[-1])).strip())
            col = col + 1

        row = row + 1
    wb.save('/tmp/output.xls')
    response = HttpResponse(open('/tmp/output.xls', 'r').read(),
                            content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment;filename=%s.xls' % unicode(
        opts).replace('.', '_')
    return response
예제 #30
0
def _contents(self):
    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):
        pass
    else:
        if isinstance(f, ListField):
            if not value:
                return conditional_escape(self.empty_value_display)
            return conditional_escape(', '.join(smart_text(v) for v in value))
    return _original(self)
예제 #31
0
def get_result_and_row_class(cl, field_name, result):
    if django.VERSION >= (1, 9):
        empty_value_display = cl.model_admin.get_empty_value_display()
    else:
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        empty_value_display = EMPTY_CHANGELIST_VALUE
    row_classes = ['field-%s' % field_name]
    try:
        f, attr, value = lookup_field(field_name, result, cl.model_admin)
    except ObjectDoesNotExist:
        result_repr = empty_value_display
    else:
        if django.VERSION >= (1, 9):
            empty_value_display = getattr(
                attr, 'empty_value_display', empty_value_display)
        if f is None:
            if field_name == 'action_checkbox':
                row_classes = ['action-checkbox']
            allow_tags = getattr(attr, 'allow_tags', False)
            boolean = getattr(attr, 'boolean', False)
            if django.VERSION >= (1, 9):
                result_repr = display_for_value(
                    value, empty_value_display, boolean)
            else:
                result_repr = display_for_value(value, boolean)
            # Strip HTML tags in the resulting text, except if the
            # function has an "allow_tags" attribute set to True.
            # WARNING: this will be deprecated in Django 2.0
            if allow_tags:
                result_repr = mark_safe(result_repr)
            if isinstance(value, (datetime.date, datetime.time)):
                row_classes.append('nowrap')
        else:
            related_field_name = 'rel' if django.VERSION <= (2, 0) else 'remote_field'
            if isinstance(getattr(f, related_field_name), models.ManyToOneRel):
                field_val = getattr(result, f.name)
                if field_val is None:
                    result_repr = empty_value_display
                else:
                    result_repr = field_val
            else:
                if django.VERSION >= (1, 9):
                    result_repr = display_for_field(
                        value, f, empty_value_display)
                else:
                    result_repr = display_for_field(value, f)
            if isinstance(f, (models.DateField, models.TimeField,
                              models.ForeignKey)):
                row_classes.append('nowrap')
        if force_str(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
    row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
    return result_repr, row_class
예제 #32
0
def _contents(self):
    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):
        pass
    else:
        if isinstance(f, ListField):
            if not value:
                return conditional_escape(self.empty_value_display)
            return conditional_escape(", ".join(smart_text(v) for v in value))
    return _original(self)
예제 #33
0
    def field_value(self, admin_model, instance, field_name):
        """Returns the value displayed in the column on the web interface for
        a given instance.

        :param admin_model:
            Instance of a :class:`admin.ModelAdmin` object that is responsible
            for displaying the change list
        :param instance:
            Object instance that is the row in the admin change list
        :field_name:
            Name of the field/column to fetch
        """
        _, _, value = lookup_field(field_name, instance, admin_model)
        return value
예제 #34
0
def link_fkey(admin_field):
    fieldname = admin_field.field["field"]
    displayed = admin_field.contents()
    obj = admin_field.form.instance
    try:
        fieldtype, attr, value = lookup_field(fieldname, obj, admin_field.model_admin)
    except ObjectDoesNotExist:
        fieldtype = None
    if isinstance(fieldtype, ForeignKey):  # XXX - probably over-simplistic wrt escaping
        try:
            admin_url = get_admin_url(value)
        except NoReverseMatch:
            admin_url = None
        if admin_url:
            displayed = u"<a href='%s'>%s</a>" % (admin_url, displayed)
    return mark_safe(displayed)
예제 #35
0
def export_as_xls(modeladmin, request, queryset):
    fields = []
    exclude_fields = []
    extras = ['']
    if not request.user.is_staff:
        raise PermissionDenied

    for f in modeladmin.list_display:
        if f not in exclude_fields:
            fields.append(f)
    fields.extend(extras)

    opts = modeladmin.model._meta
    wb = Workbook()
    ws0 = wb.add_sheet('ss')
    col = 0
    field_names = []
    # describe cabecera fila
    ##	for field in field_names:
    for field in fields:
        ws0.write(0, col, field)
        field_names.append(field)
        col = col + 1
    row = 1
    #ahora la data en cada fila en columnas
    for obj in queryset:
        col = 0
        for field in field_names:
            if field in extras:
                try:
                    val = [eval('obj.' + field)]
                except:
                    val = ['None']
            else:
                try:
                    val = lookup_field(field, obj, modeladmin)
                except:
                    val = ['None']
            ws0.write(row, col, str((val[-1])).strip())
            col = col + 1
        row = row + 1
    wb.save('/tmp/output.xls')
    response = HttpResponse(open('/tmp/output.xls', 'r').read(),
                            content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment;filename=%s.xls' % unicode(
        opts).replace('.', '_')
    return response
예제 #36
0
    def test_values_from_lookup_field(self):
        """
        Regression test for #12654: lookup_field
        """
        SITE_NAME = "example.com"
        TITLE_TEXT = "Some title"
        CREATED_DATE = datetime.min
        ADMIN_METHOD = "admin method"
        SIMPLE_FUNCTION = "function"
        INSTANCE_ATTRIBUTE = "attr"

        class MockModelAdmin:
            def get_admin_value(self, obj):
                return ADMIN_METHOD

        def simple_function(obj):
            return SIMPLE_FUNCTION

        site_obj = Site(domain=SITE_NAME)
        article = Article(
            site=site_obj,
            title=TITLE_TEXT,
            created=CREATED_DATE,
        )
        article.non_field = INSTANCE_ATTRIBUTE

        verifications = (
            ("site", SITE_NAME),
            ("created", localize(CREATED_DATE)),
            ("title", TITLE_TEXT),
            ("get_admin_value", ADMIN_METHOD),
            (simple_function, SIMPLE_FUNCTION),
            ("test_from_model", article.test_from_model()),
            ("non_field", INSTANCE_ATTRIBUTE),
        )

        mock_admin = MockModelAdmin()
        for name, value in verifications:
            field, attr, resolved_value = lookup_field(name, article,
                                                       mock_admin)

            if field is not None:
                resolved_value = display_for_field(resolved_value, field,
                                                   self.empty_value)

            self.assertEqual(value, resolved_value)
예제 #37
0
def export_as_csv(admin_model, request, queryset):
    """
    Generic csv export admin action.
    based on http://djangosnippets.org/snippets/1697/
    """

    # everyone has perms to export as csv unless explicitly defined
    if getattr(settings, 'DJANGO_EXPORTS_REQUIRE_PERM', None):
        admin_opts = admin_model.opts
        codename = '%s_%s' % ('csv', admin_opts.object_name.lower())
        has_csv_permission = request.user.has_perm(
            "%s.%s" % (admin_opts.app_label, codename))
    else:
        try:
            has_csv_permission = admin_model.has_csv_permission(request)
        except (AttributeError, TypeError):
            has_csv_permission = True

    if not has_csv_permission:
        return HttpResponseForbidden()

    opts = admin_model.model._meta
    if getattr(admin_model, 'csv_fields', None):
        field_names = admin_model.csv_fields
    else:
        field_names = [field.name for field in opts.fields]
        field_names.sort()

    if django.VERSION[0] == 1 and django.VERSION[1] <= 5:
        response = HttpResponse(mimetype='text/csv')
    else:
        response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s.csv' % text(
        opts).replace('.', '_')

    writer = csv.writer(response)
    writer.writerow(list(field_names))
    for obj in queryset.iterator():
        values = []
        for field in field_names:
            f, attr, value = lookup_field(field, obj, admin_model)
            values.append(value)
        writer.writerow(values)

    return response
예제 #38
0
파일: tests.py 프로젝트: poleha/django
    def test_values_from_lookup_field(self):
        """
        Regression test for #12654: lookup_field
        """
        SITE_NAME = 'example.com'
        TITLE_TEXT = 'Some title'
        CREATED_DATE = datetime.min
        ADMIN_METHOD = 'admin method'
        SIMPLE_FUNCTION = 'function'
        INSTANCE_ATTRIBUTE = 'attr'

        class MockModelAdmin(object):
            def get_admin_value(self, obj):
                return ADMIN_METHOD

        def simple_function(obj):
            return SIMPLE_FUNCTION

        site_obj = Site(domain=SITE_NAME)
        article = Article(
            site=site_obj,
            title=TITLE_TEXT,
            created=CREATED_DATE,
        )
        article.non_field = INSTANCE_ATTRIBUTE

        verifications = (('site', SITE_NAME), ('created',
                                               localize(CREATED_DATE)),
                         ('title', TITLE_TEXT), ('get_admin_value',
                                                 ADMIN_METHOD),
                         (simple_function,
                          SIMPLE_FUNCTION), ('test_from_model',
                                             article.test_from_model()),
                         ('non_field', INSTANCE_ATTRIBUTE))

        mock_admin = MockModelAdmin()
        for name, value in verifications:
            field, attr, resolved_value = lookup_field(name, article,
                                                       mock_admin)

            if field is not None:
                resolved_value = display_for_field(resolved_value, field,
                                                   self.empty_value)

            self.assertEqual(value, resolved_value)
예제 #39
0
    def report(modeladmin, request, queryset):
        results = {'header': [], 'results': []}
        for field_name in fields:
            text, attr = label_for_field(field_name,
                                         modeladmin.model,
                                         model_admin=modeladmin,
                                         return_attr=True)
            results['header'].append(text.capitalize())

        for obj in queryset:
            line = []
            for field_name in fields:
                f, attr, value = lookup_field(field_name, obj, modeladmin)
                if f is None or f.auto_created:
                    boolean = getattr(attr, 'boolean', False)
                    result_repr = display_for_value(value, boolean)
                else:
                    if isinstance(f.rel, models.ManyToOneRel):
                        field_val = getattr(obj, f.name)
                        if field_val is None:
                            result_repr = '-'
                        else:
                            result_repr = field_val
                    else:
                        result_repr = display_for_field(value, f, '-')
                line.append(strip_tags(u'%s' % result_repr))
            results['results'].append(line)

        template = get_template(template_name)
        html = template.render(
            RequestContext(request, {
                'header': header,
                'results': results,
            }))
        result = StringIO.StringIO()
        pdf = pisaDocument(
            StringIO.StringIO(html.encode("UTF-8")),
            dest=result,
            link_callback=lambda uri, rel: os.path.join(
                settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")))
        if not pdf.err:
            return HttpResponse(result.getvalue(),
                                content_type='application/pdf')
        return HttpResponse('We had some errors<pre>%s</pre>' %
                            cgi.escape(html))
예제 #40
0
    def getter(self, obj):
        last_obj = obj
        related_name = None

        for related_name in related_names:
            last_obj = obj
            try:
                obj = getattr(obj, "get_%s_display" % related_name)()
            except AttributeError:
                obj = getattr(obj, related_name, None)
        if callable(obj):
            obj = obj()
        elif isinstance(last_obj, models.Model):
            f, attr, value = lookup_field(related_name, last_obj, self)
            empty_value_display = get_empty_value_display(self)
            empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
            obj = display_for_field(value, f, empty_value_display)
        return obj
예제 #41
0
파일: options.py 프로젝트: mrmuxl/keops
 def db_read(self, request):
     try:
         p = request.GET.get('p')
         pk = request.GET.get('pk')
         if p:
             obj = self.model.objects.all()[int(p)]
         elif pk:
             obj = self.model.objects.get(pk=request.GET.get('pk'))
         data = {'pk': obj.pk}
         if not self.fields:
             self.fields = ['name']
         for f in self.fields:
             data[f] = lookup_field(f, obj, self)[2]
         data = [data]
     except:
         raise
         data = {}
     return JsonResponse({'items': data})
예제 #42
0
    def getter(self, obj):
        last_obj = obj
        related_name = None

        for related_name in related_names:
            last_obj = obj
            try:
                obj = getattr(obj, "get_%s_display" % related_name)()
            except AttributeError:
                obj = getattr(obj, related_name, None)
        if callable(obj):
            obj = obj()
        elif isinstance(last_obj, models.Model):
            f, attr, value = lookup_field(related_name, last_obj, self)
            empty_value_display = get_empty_value_display(self)
            empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
            obj = display_for_field(obj, f, empty_value_display)
        return obj
예제 #43
0
    def test_values_from_lookup_field(self):
        """
        Regression test for #12654: lookup_field
        """
        SITE_NAME = 'example.com'
        TITLE_TEXT = 'Some title'
        CREATED_DATE = datetime.min
        ADMIN_METHOD = 'admin method'
        SIMPLE_FUNCTION = 'function'
        INSTANCE_ATTRIBUTE = 'attr'

        class MockModelAdmin(object):
            def get_admin_value(self, obj):
                return ADMIN_METHOD

        def simple_function(obj):
            return SIMPLE_FUNCTION

        site_obj = Site(domain=SITE_NAME)
        article = Article(
            site=site_obj,
            title=TITLE_TEXT,
            created=CREATED_DATE,
        )
        article.non_field = INSTANCE_ATTRIBUTE

        verifications = (('site', SITE_NAME),
                         ('created', localize(CREATED_DATE)), ('title',
                                                               TITLE_TEXT),
                         ('get_admin_value', ADMIN_METHOD), (simple_function,
                                                             SIMPLE_FUNCTION),
                         ('test_from_model', article.test_from_model()),
                         ('non_field', INSTANCE_ATTRIBUTE))

        mock_admin = MockModelAdmin()
        for name, value in verifications:
            field, attr, resolved_value = lookup_field(name, article,
                                                       mock_admin)

            if field is not None:
                resolved_value = display_for_field(resolved_value, field,
                                                   self.empty_value)

            self.assertEqual(value, resolved_value)
예제 #44
0
 def make_info_panel(self):
     pin_fields = [
         'actived', 'deleted', 'created', 'creator', 'modified', 'operator',
         'onidc', 'mark'
     ]
     exclude = [
         'id', 'password', 'user_permissions', 'onidc', 'actived',
         'deleted', 'mark'
     ]
     base_fields = list(fields_for_model(self.model, exclude=exclude))
     new_pin_fields = [i for i in pin_fields if i in base_fields]
     fields = [
         f for f in base_fields
         if f not in new_pin_fields and f not in exclude
     ]
     fields.extend(new_pin_fields)
     default_fields = getattr(self.opts, 'list_display', None)
     if default_fields and isinstance(default_fields, list):
         o = [f for f in fields if f not in default_fields]
         default_fields.extend(o)
         fields = default_fields
     panel = ''
     for index, field_name in enumerate(fields, 1):
         tr_format = '<tr><th>{th}</th><td>{td}</td>'
         th = label_for_field(name=field_name, model=self.model)
         try:
             field = self.opts.get_field(field_name)
             value = field.value_from_object(self.object)
             td = display_for_field(value, field, only_date=False)
         except BaseException:
             try:
                 f, _, td = lookup_field(field_name, self.object,
                                         self.model)
             except BaseException:
                 pass
         if (index % 2 == 0):
             append = '<tr class="visible-xs"><th>{th}</th><td>{td}</td></tr>'
             _format = '<th class="hidden-xs">{th}</th><td class="hidden-xs">{td}</td></tr>'
             tr_format = _format + append
         tr_html = tr_format.format(th=th, td=td)
         panel += tr_html
     return mark_safe(panel)
def items_for_result(view, result):
    """
    Generates the actual list of data.
    """
    model_admin = view.model_admin
    for field_name in view.list_display:
        empty_value_display = ""
        row_classes = ["field-%s" % field_name]
        try:
            f, attr, value = lookup_field(field_name, result, model_admin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, "empty_value_display", empty_value_display)
            if f is None or f.auto_created:
                allow_tags = getattr(attr, "allow_tags", False)
                boolean = getattr(attr, "boolean", False)
                if boolean or not value:
                    allow_tags = True
                result_repr = display_for_value(value, boolean)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append("nowrap")
            else:
                if isinstance(f, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append("nowrap")
        if force_text(result_repr) == "":
            result_repr = mark_safe("&nbsp;")
        row_class = mark_safe(' class="%s"' % " ".join(row_classes))
        yield format_html("<td{}>{}</td>", row_class, result_repr)
예제 #46
0
        def generate_response():
            csv = UnicodeWriter(pseudo_buffer,
                                fieldnames=res_headers.values(),
                                delimiter=str(delimiter))

            for result in cl.queryset.iterator():
                row = {}
                for field_name in cl.list_display:
                    if field_name == 'action_checkbox':
                        continue
                    try:
                        _, _, value = lookup_field(field_name, result,
                                                   cl.model_admin)
                    except ObjectDoesNotExist:
                        value = None

                    if isinstance(value, six.string_types):
                        value = strip_tags(value)
                    row[res_headers[field_name]] = value

                yield csv.writerow(row)
예제 #47
0
def list_field_value(view, obj, field, context, index):
    value = ''
    try:
        # Use django.admin's function to render the list_display column value
        # lookup_field expects a ModelAdmin instance as the third argument,
        # but all it does is dyanamic lookup of the field as a method of this
        # object and if found, evaluates it to return the value. So it's safe
        # to pass it a ViewSet instance. Of course, if the lookup_field
        # implementation changes, we'll to change this code accordingly.
        f, _, value = lookup_field(field, obj, view._viewset)

        # for fields that have 'choices=' set conver the value into its
        # more descriptive string.
        if getattr(f, 'choices', None):
            choices = dict(f.choices)
            if value in choices:
                value = dict(choices)[value]

    except AttributeError:
        f, _, value = (None, None, '')

    if index == 0:
        detail_url = view._viewset.get_detail_url(obj)
        if detail_url:
            title = ugettext("{0} Detail").format(
                view._viewset.model._meta.verbose_name)
            if view._viewset.popups['detail']:
                value = six.text_type(
                    '<a name="object_detail" data-url="{0}" data-title="{2}" href="javascript:void(0);">{1}</a>'
                ).format(detail_url, value, title)
            else:
                value = six.text_type(
                    '<a href="{0}" title="{2}">{1}</a>').format(
                        detail_url, value, title)

        return mark_safe(
            six.text_type("{0}<div data-name='{1}'></div>").format(
                value, view._viewset.get_obj_name(obj)))

    return value
예제 #48
0
    def test_values_from_lookup_field(self):
        """
        Regression test for #12654: lookup_field
        """
        SITE_NAME = "example.com"
        TITLE_TEXT = "Some title"
        CREATED_DATE = datetime.min
        ADMIN_METHOD = "admin method"
        SIMPLE_FUNCTION = "function"
        INSTANCE_ATTRIBUTE = "attr"

        class MockModelAdmin:
            def get_admin_value(self, obj):
                return ADMIN_METHOD

        def simple_function(obj):
            return SIMPLE_FUNCTION

        site_obj = Site(domain=SITE_NAME)
        article = Article(site=site_obj, title=TITLE_TEXT, created=CREATED_DATE)
        article.non_field = INSTANCE_ATTRIBUTE

        verifications = (
            ("site", SITE_NAME),
            ("created", localize(CREATED_DATE)),
            ("title", TITLE_TEXT),
            ("get_admin_value", ADMIN_METHOD),
            (simple_function, SIMPLE_FUNCTION),
            ("test_from_model", article.test_from_model()),
            ("non_field", INSTANCE_ATTRIBUTE),
        )

        mock_admin = MockModelAdmin()
        for name, value in verifications:
            field, attr, resolved_value = lookup_field(name, article, mock_admin)

            if field is not None:
                resolved_value = display_for_field(resolved_value, field, self.empty_value)

            self.assertEqual(value, resolved_value)
예제 #49
0
        def generate_response():
            csv = UnicodeWriter(
                pseudo_buffer,
                fieldnames=res_headers.values(),
                delimiter=str(delimiter))

            for result in cl.queryset.iterator():
                row = {}
                for field_name in cl.list_display:
                    if field_name == 'action_checkbox':
                        continue
                    try:
                        _, _, value = lookup_field(
                            field_name, result, cl.model_admin)
                    except ObjectDoesNotExist:
                        value = None

                    if isinstance(value, six.string_types):
                        value = strip_tags(value)
                    row[res_headers[field_name]] = value

                yield csv.writerow(row)
예제 #50
0
파일: generic.py 프로젝트: nirgal/ngw
    def action_csv_export(self, request, queryset):
        result = ''

        def _quote_csv(col_html):
            u = html.strip_tags(str(col_html))
            u = u.rstrip('\n\r')  # remove trailing \n
            # drop spaces at the begining of the line:
            u = re.sub('^[ \t\n\r\f\v]+', '', u, flags=re.MULTILINE)
            u = re.sub('[ \t\n\r\f\v]*\n', '\n', u)  # remove duplicates \n
            # Unquote
            u = u.replace('&quot;', '"').replace('&#39;', "'")
            # Do the actual escaping/quoting (quotes doubling for libreoffice)
            return '"' + u.replace('"', '""') + '"'

        header_done = False
        for row in queryset:
            if not header_done:
                for i, field_name in enumerate(self.list_display):
                    text, attr = label_for_field(
                        field_name, type(row), self, True)
                    if i:  # not first column
                        result += ','
                    result += _quote_csv(text)
                result += '\n'
                header_done = True
            for i, field_name in enumerate(self.list_display):
                if i:  # not first column
                    result += ','
                f, attr, value = lookup_field(field_name, row, self)
                if value is None:
                    continue
                if f is None:
                    col_html = display_for_value(value, False)
                else:
                    col_html = display_for_field(value, f)

                result += _quote_csv(col_html)
            result += '\n'
        return HttpResponse(result, content_type='text/csv; charset=utf-8')
예제 #51
0
    def get_field_val(self, obj, key):
        """
        Follows the same rules as ModelAdmin dynamic lookups:

        1. Model field
        2. Callable
        3. Method on table
        4. Method on model
        5. Other attribute on model

        Returns a value which will be passed to the template.
        """
        # Compare:
        # * django.contrib.admin.utils:display_for_field
        # * django.contrib.admin.utils:display_for_value
        field, attr, value = lookup_field(key, obj, self)

        if field is not None:
            if field.flatchoices:
                return dict(field.flatchoices).get(value, '(None)')

        return value
예제 #52
0
def items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """

    for field_name in cl.list_display:
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            allow_tags = getattr(attr, "allow_tags", False)
            boolean = getattr(attr, "boolean", False)
            if boolean:
                allow_tags = True
            result_repr = display_for_value(value, boolean)
            # Strip HTML tags in the resulting text, except if the
            # function has an "allow_tags" attribute set to True.
            if allow_tags:
                result_repr = mark_safe(result_repr)

        yield result_repr
예제 #53
0
def get_result_and_row_class(cl, field_name, result):
    row_class = ''
    try:
        f, attr, value = lookup_field(field_name, result, cl.model_admin)
    except ObjectDoesNotExist:
        # result_repr = EMPTY_CHANGELIST_VALUE
        result_repr = get_empty_value_display(cl)
    else:
        if f is None:
            if field_name == 'action_checkbox':
                row_class = mark_safe(' class="action-checkbox"')
            allow_tags = getattr(attr, 'allow_tags', False)
            boolean = getattr(attr, 'boolean', False)
            if boolean:
                allow_tags = True
            result_repr = display_for_value(value, boolean)
            # Strip HTML tags in the resulting text, except if the
            # function has an "allow_tags" attribute set to True.
            if allow_tags:
                result_repr = mark_safe(result_repr)
            if isinstance(value, (datetime.date, datetime.time)):
                row_class = mark_safe(' class="nowrap"')
        else:
            if isinstance(f.rel, models.ManyToOneRel):
                field_val = getattr(result, f.name)
                if field_val is None:
                    # result_repr = EMPTY_CHANGELIST_VALUE
                    result_repr = get_empty_value_display(cl)
                else:
                    result_repr = field_val
            else:
                result_repr = display_for_field(value, f)
            if isinstance(f, (models.DateField, models.TimeField,
                              models.ForeignKey)):
                row_class = mark_safe(' class="nowrap"')
        if force_str(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
    return result_repr, row_class
예제 #54
0
def get_value(obj, field, modeladmin, keep_type=False):
    if '__' in field:
        # field is a related object. Start recursion.
        s = field.split('__')

        # check if obj is a dict or a object
        if isinstance(obj, dict):
            next_obj = obj.get(s[0], None)
        else:
            next_obj = getattr(obj, s[0], None)

        return get_value(next_obj, '__'.join(s[1:]), modeladmin)
    else:
        val = ''
        try:
            val = lookup_field(field, obj, modeladmin)
            if isinstance(val[0], ManyToManyField):
                val = '; '.join([u'%s' % a for a in val[-1].all()])
            else:
                val = val[-1]
        except Exception as e:
            attr = getattr(obj, field, None)
            try:
                if callable(attr):
                    val = attr()
                elif isinstance(obj, dict):
                    val = obj.get(field, None)
                else:
                    logger.warning('Field not found: {} from {}'.format(
                        field, obj))
            except Exception as e:
                logger.exception('Not able to extract for {}'.format(field))
                return val

        if keep_type:
            return val

        return primitive_value(val)
예제 #55
0
 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)
예제 #56
0
def inline_items_for_result(inline, result):
    """
    Generates the actual list of data for the inline.
    """
    list_display = inline.list_display if inline.list_display else ('__unicode__',)
    ret = ''
    for field_name in list_display:
        row_class = mark_safe(' class="column"')
        try:
            f, attr, value = lookup_field(field_name, result, inline)
        except ObjectDoesNotExist:
            result_repr = ''
        else:
            if f is None:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                result_repr = display_for_value(value, boolean)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    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 = ''
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f)
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')

        ret += format_html(u'<span{0}>{1}</span>', row_class, result_repr)
    return ret
예제 #57
0
파일: admin_list.py 프로젝트: edevil/django
def items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """

    def link_in_col(is_first, field_name, cl):
        if cl.list_display_links is None:
            return False
        if is_first and not cl.list_display_links:
            return True
        return field_name in cl.list_display_links

    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_classes = ['field-%s' % field_name]
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if f is None:
                if field_name == 'action_checkbox':
                    row_classes = ['action-checkbox']
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                result_repr = display_for_value(value, boolean)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            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 = field_val
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
        # If list_display_links not defined, add the link tag to the first field
        if link_in_col(first, field_name, cl):
            table_tag = 'th' if first else 'td'
            first = False

            # Display link to the result's change_view if the url exists, else
            # display just the result's representation.
            try:
                url = cl.url_for_result(result)
            except NoReverseMatch:
                link_or_text = result_repr
            else:
                url = add_preserved_filters({'preserved_filters': cl.preserved_filters, 'opts': cl.opts}, url)
                # 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 = escapejs(value)
                link_or_text = format_html(
                    '<a href="{}"{}>{}</a>',
                    url,
                    format_html(
                        ' onclick="opener.dismissRelatedLookupPopup(window, '
                        '&#39;{}&#39;); return false;"', result_id
                    ) if cl.is_popup else '',
                    result_repr)

            yield format_html('<{}{}>{}</{}>',
                              table_tag,
                              row_class,
                              link_or_text,
                              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 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))
            yield format_html('<td{}>{}</td>', row_class, result_repr)
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html('<td>{}</td>', force_text(form[cl.model._meta.pk.name]))
예제 #58
0
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('&nbsp;')

        # #### 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]))
예제 #59
0
def items_for_result(cl, result, form):
    """
    Generate the actual list of data.
    """

    def link_in_col(is_first, field_name, cl):
        if cl.list_display_links is None:
            return False
        if is_first and not cl.list_display_links:
            return True
        return field_name in cl.list_display_links

    first = True
    pk = cl.lookup_opts.pk.attname
    for field_index, field_name in enumerate(cl.list_display):
        empty_value_display = cl.model_admin.get_empty_value_display()
        row_classes = ['field-%s' % _coerce_field_name(field_name, field_index)]
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
            if f is None or f.auto_created:
                if field_name == 'action_checkbox':
                    row_classes = ['action-checkbox']
                boolean = getattr(attr, 'boolean', False)
                result_repr = display_for_value(value, empty_value_display, boolean)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                if isinstance(f.remote_field, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f, empty_value_display)
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if str(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
        # If list_display_links not defined, add the link tag to the first field
        if link_in_col(first, field_name, cl):
            table_tag = 'th' if first else 'td'
            first = False

            # Display link to the result's change_view if the url exists, else
            # display just the result's representation.
            try:
                url = cl.url_for_result(result)
            except NoReverseMatch:
                link_or_text = result_repr
            else:
                url = add_preserved_filters({'preserved_filters': cl.preserved_filters, 'opts': cl.opts}, url)
                # Convert the pk to something that can be used in Javascript.
                # Problem cases are non-ASCII strings.
                if cl.to_field:
                    attr = str(cl.to_field)
                else:
                    attr = pk
                value = result.serializable_value(attr)
                link_or_text = format_html(
                    '<a href="{}"{}>{}</a>',
                    url,
                    format_html(
                        ' data-popup-opener="{}"', value
                    ) if cl.is_popup else '',
                    result_repr)

            yield format_html('<{}{}>{}</{}>', table_tag, row_class, link_or_text, 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 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(str(bf.errors) + str(bf))
            yield format_html('<td{}>{}</td>', row_class, result_repr)
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html('<td>{}</td>', form[cl.model._meta.pk.name])