Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how to change the choices of AdminTimeWidget

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"?

like image 374
Mermoz Avatar asked Apr 24 '11 14:04

Mermoz


People also ask

How do I override a Django form?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

How do you remove save and add another Django admin?

The simplest option is to set save_as=True on the ModelAdmin . This will replace the "Save and add another" button with a "Save as new" button.

What is Attrs Django?

attrs . A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren't set, Widget. attrs is used instead.


2 Answers

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 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);
like image 69
Brian Fisher Avatar answered Sep 22 '22 21:09

Brian Fisher


I went with a much simpler approach and it worked for me. I simply added choices to my model using the following code:

class Class(Model): program = ForeignKey('Program') time_of_the_day = TimeField(choices=( (datetime.datetime.strptime('7:00 am', "%I:%M %p").time(), '7:00 am'), (datetime.datetime.strptime('8:00 am', "%I:%M %p").time(), '8:00 am'), (datetime.datetime.strptime('9:00 am', "%I:%M %p").time(), '9:00 am'), (datetime.datetime.strptime('6:00 pm', "%I:%M %p").time(), '6:00 pm'), (datetime.datetime.strptime('7:00 pm', "%I:%M %p").time(), '7:00 pm'), (datetime.datetime.strptime('8:00 pm', "%I:%M %p").time(), '8:00 pm'), (datetime.datetime.strptime('9:00 pm', "%I:%M %p").time(), '9:00 pm'),
))

Hope this helps

like image 36
Bit68 Avatar answered Sep 19 '22 21:09

Bit68