Enabling Floating Table Headers in Django Admin
To anyone who’s used Django’s amazing admin interface to browse large record lists, you’ve probably felt the frustration of having to scroll up and down the list to remind yourself of a column’s header name. Fortunately, there’s a trivial change you can make to Django’s base admin template to make your life easier. Enter the jQuery floating header plugin. As the name suggests, it auto-magically makes the header of tables float when you scroll down the table, so that the header is always in view.
To incorporate this library into Django’s admin, follow these steps:
1. Add jquery.floatheader.js to your media. I put mine in <workspace>/media/js/lib. I’ve arranged my URL patterns so that admin and non-admin media start from the same root URL. This allows me to easily use a relative “..” path to resolve to one or the other without knowing the root.
2. In your default templates directory, ensure there’s an admin subdirectory, and in there create a file called “base_site.html” with the content:
{% extends "admin/base.html" %}
{% load i18n admin_modify adminmedia %}
{% block extrahead %}{{ block.super }}
<script language="javascript" src="{% admin_media_prefix %}../js/lib/jquery.js"></script>
<script language="javascript" src="{% admin_media_prefix %}../js/lib/jquery.floatheader.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function($){
$('<insert your table pattern here>').floatHeader();
});
})(jQuery);
</script>
{% endblock %}3. Replace “<insert your table pattern here>” with a CSS selector of the table you’d like to float. I find Firebug useful for inspecting the CSS classes to identify the ones I want. For example, “‘.tabular fieldset table” is what you’d use to float the header on tabular inlines. You can include additional lines in ready() for each pattern.
To summarize, this modification defines an extra Javascript include in every admin page in order to load the jquery.floatheader.js plugin and then applies it to every table matching the pattern you specify.
Note, I’m also explicitly including jQuery even though it’s already available in admin via the variable django.jQuery. Unfortunately, I couldn’t find an easy way to access it in this template, as it seems to be defined later in the parent template, so attempts to access it here result in an “undefined variable” error. Django’s version of jQuery tends to lag behind the most recent version, so I tend not to rely on it regardless.
Otherwise, that’s all there is to it. I found this so surprisingly useful and easy to add to my current projects, I’m surprised this functionality isn’t included by default in admin.
No Comments »
Filed under: Django, Javascript, Uncategorized, jQuery