Django: how to change the choices of AdminTimeWidget

后端 未结 6 1768
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 12:29

The AdminTimeWidget rendered in admin for a DateTimeField displays an icon of a clock and when you click you have the choice between: \"Now Midnigh

6条回答
  •  时光取名叫无心
    2020-12-08 12:38

    There's better solution. After reading DateTimeShortcuts.js the can be simplified to:

    (function ($) {
        $(document).ready(function () {
    
            DateTimeShortcuts.clockHours.default_ = [];
    
            for (let hour = 8; hour <= 20; hour++) {
                let verbose_name = new Date(1970, 1, 1, hour, 0, 0).strftime('%H:%M');
                DateTimeShortcuts.clockHours.default_.push([verbose_name, hour])
            }
    
        });
    })(django.jQuery);
    

    Then add this code to the javascript file in 'static//time-shortcuts.js' and add Meta to your admin model:

    from django.contrib import admin
    from .models import MyModel
    
    @admin.register(MyModel)
    class MyModelAdmin(admin.ModelAdmin):
        class Media:
            js = [
                '/time-shortcuts.js',
            ]
    

提交回复
热议问题