views:

36

answers:

1

How can I change the output result from Django Admin Result List? I've been looking into the change_result_list.html template file but all I can find is :

{% for item in result %}{{ item }}{% endfor %}

Which will be outputting something like :

<tr>
    <td>
        <input type="checkbox" class="action-select" value="2" name="_selected_action" />
    </td>
    <th>
        <a href="1/">Lorem Ipsum</a>
    </th>
</tr>

Obviously, the th element breaks my design. Is there anyway to change it into td?

A: 

There's no "easy" way to do it, so I must first ask why exactly you need to do this at all. I don't see why the <th> element should "obviously" break your design. The <th> element is equivalent to <td>, except that is has extra styling by default (usually font-weight: bold; text-align: center;). You should be able to account for this in your CSS.

That said, here are some avenues to look at. The th/td choice is determined on line 169 (Django 1.2.1) of django.contrib.admin.templatetags.admin_list.py. Here's a snipped summary of the context it appears in:

def items_for_result(cl, result, form):
    first = True
    for field_name in cl.list_display:
        # ...
        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
            # ...
            yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % (table_tag, row_class, url, ...)
        else:
            # ...
            yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr))

As you can see, there's no obvious way to alter the behaviour that determines the value of table_tag, so some of the options you have are:

  • Define a "items_for_result" templatetag that calls the one above and replaces any <th>s in the yielded values with <td>s. Then you can override "change_list.html" and {% load %} the tag after "admin_list" is loaded.
  • Edit the Django code. You'll regret it later though.
  • If you're OK with none of the columns in the table being a link to the edit page for the item (I can't imagine why you would), you can use this ugly hack in your admin.py:

    admin.site.register(YourModel, YourModelAdmin)
    admin.site._registry[YourModel].list_display_links = ['not_a_field_name',]`
    

    Since the admin models are only validated once, which happens when register() is called, you can fetch the registered ModelAdmin afterwards and give it an invalid list_display_links property.

Aram Dulyan
Indeed, editing the CSS is much easier. However, from usability point of view (and my idealism), th should only be used for a header cell. It's just kind of ridiculous why they use th instead of td.
Furuno