Best django-admin questions in April 2011

Django: how to change the choices of AdminTimeWidget

5 votes

The AdminTimeWidget rendered in admin for a DateTimeField displays an icon of a clock and when you click you have the choice between: "Now Midnight 6:00 Noon".

How can I change these choices to "16h 17h 18h"?

Chris has a great answer. As an alternative you could do this using just javascript. Place the following javascript on the pages where you want the different time options.

DateTimeShortcuts.overrideTimeOptions = function () {
    //Find the first time element
    timeElement = django.jQuery("ul.timelist li").eq(0).clone();
    originalHref = timeElement.find('a').attr('href');

    //remove all existing time elements
    django.jQuery("ul.timelist li").remove();

    //add new time elements representing those you want
    var i=0;
    for (i=0;i<=23;i++) {
        //use a regular expression to update the the link
        newHref = originalHref.replace(/Date\([^\)]*\)/g, "Date(1970,1,1," + i + ",0,0,0)");
        //update the text for the element
        timeElement.find('a').attr('href', newHref).text(i+"h");
        //Add the new element into the document
        django.jQuery("ul.timelist").append(timeElement.clone());
    }
}

addEvent(window, 'load', DateTimeShortcuts.overrideTimeOptions);