Adding object tools to Django admin pages

Sometimes I want to add an item to the list of “object tools” on the change form for a model. The base admin/change_form.html template, however, does not (as of Django 1.0.2) include a block inside the object tools list:

<ul class="object-tools">
  <li><a href="history/" class="historylink">{% trans "History" %}</a></li>
  {% if has_absolute_url %}
    <li>
      <a href="../../../r/{{ content_type_id }}/{{ object_id }}/" 
         class="viewsitelink">{% trans "View on site" %}</a>
    </li>
  {% endif%}
</ul>

I don’t want to reproduce this code to add something to the list, so instead I write a JavaScript function with jQuery:

function appendObjectTools(tools) {
    /* Appends items to the object tool list.
     *
     * 'tools' param is an Array of Objects in which each Object
     * has 'url' and 'title' properties corresponding to the
     * URL and href for each link.
     */
    html = '';
    for (var i=0; i < tools.length; i++) {
	html += '<li><a href="' + tools[i].url + '">' + tools[i].title + '</a></li>';
    }
    $('#content-main .object-tools').append(html);
}

I can then override the change form for a model:

{% extends "admin/change_form.html" %}
{% block extrahead %}
    {{ block.super }}
    <script type="text/javascript">
$(function() {
    tools = [
        {
            url: "{% url collections id=original.id %}",
            title: "Collections"
        }
    ];
    appendObjectTools(tools);
});
    </script>
{% endblock %}

jQuery and the custom script function can be added using ModelAdmin media definitions.

Now on my change form I get a pretty oval button. 🙂

Advertisements

, ,