filter

Django filter hack

Posted by andu
Tue, 2006-03-07 10:52

One of the problems I faced when using Django's admin was the filter part overlapped the table with data, when I showed lots of fields in the admin listing.

Martin demanded a fix, so I did a quick hack today and made it toggable ( ie you can toggle up and toggle down the filter pane). If you want to aply a filter, show it. If not, leave it there and browse the listings.

I know it could have been done with just some simple javascript that manipulates the display css property, thus avoiding loading 3 js files, but I liked the effect. :) If anyone wants a slimmed version, let me know and I'll post one.

Here's what you have to do:

  • Download moo.fx.js, moo.fx.pack.js and prototype.lite.js from moo.fx
  • Put them somewhere in the head section of admin/base.html template. In my case:
    <script type="text/javascript" src="/static/js/admin/prototype.lite.js">
    </script>
    <script type="text/javascript" src="/static/js/admin/moo.fx.js">
    </script>
    <script type="text/javascript" src="/static/js/admin/moo.fx.pack.js">
    </script>
    
  • Add the following code to the head, the same file:
    <script type="text/javascript">
        var filtruEff;
        
        function addEvent(object, type, handler)
        {
            if (object.addEventListener) {
                object.addEventListener(type, handler, false);
            } else if (object.attachEvent) {
                object.attachEvent(['on',type].join(''),handler);
            } else {
                object[['on',type].join('')] = handler;
            }
        } 
    
        addEvent(window,"load",filtruHandler);
        
        function filtruHandler() {
            var x = document.getElementById("filtruDiv");
            if (!x)
                return;
                    
            filtruEff = new fx.Combo('filtruDiv', {opacity:true, duration:600});
            filtruEff.hide();
        }
    
    </script>
    
  • Modify the admin/filters.html template to look like this:
    {% load admin_list %}
    {% if cl.has_filters %}<div id="changelist-filter">
    <h2>Filter (<a href="javascript:filtruEff.toggle();">Toggle</a>)</h2>
    <div id="filtruDiv">
    {% for spec in cl.filter_specs %}
       {% filter cl spec %}
    {% endfor %}</div>
    </div>
    {% endif %}