3

I'm overriding my model admin form in order to change the format of the displayed time of a TimeField field:

class myTimeForm(forms.ModelForm):
    start_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))
    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = myTimeForm

Now, the now and the clock button I had with the default form have disappeared (in the screenshot below Start time is with the overridden widget, End time with the default one.

enter image description here

What did I miss?

jul
  • 36,404
  • 64
  • 191
  • 318

1 Answers1

4

The Django admin uses the AdminTimeWidget instead of forms.TimeInput. Try changing your code to the following:

from django.contrib.admin.widgets import AdminTimeWidget

class myTimeForm(forms.ModelForm):
    start_time = forms.TimeField(widget=AdminTimeWidget(format='%H:%M'))
    class Meta:
        model = MyModel
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • No, `AdminTimeWidget` is not currently documented. You can see that it's the default widget for `models.TimeField` in the Django admin by looking at [the code](https://github.com/django/django/blob/ff05de760cc4ef4c7f188e163c722ec3bc1f0cbf/django/contrib/admin/options.py#L78). – Alasdair Feb 01 '18 at 13:37
  • gotcha .. Thanks. Apparently, setting the format is not working :(. Tried it with every combination. placed in __init__ to override the field widget also. Still, not working. – cedzz Feb 01 '18 at 13:55
  • That's not enough information for anyone to help you. It would be better to ask a new question rather than commenting on a 5-year old question. – Alasdair Feb 01 '18 at 14:03
  • Yes, that's what I thought, will do :). For starters, I just used the exactly similar pattern written above and register it to admin like `admin.site.register(MyModel, MyModelAdmin)` and it's not detecting the format parameter value while showing in the admin page. – cedzz Feb 01 '18 at 14:13
  • 1
    I just tested the above code in Django 1.11 and it still works for me. – Alasdair Feb 01 '18 at 14:25
  • I just tested the whole flow, the problem is that while creating/setting the value first time using `now` or `clock` button, it is showing in the default format. After saving and refreshing - it is showing it in the desired passed format :). I should have tested the whole flow. I think I can live with this for now. I hope you get what I am saying. BTW, Thanks for help. – cedzz Feb 01 '18 at 14:34
  • Since those buttons use JavaScript to populate the fields, it might be quite tricky to get them to work. You might be better to look for a different widget, rather than trying to customise the undocumented `AdminTimeWidget`. – Alasdair Feb 01 '18 at 14:40
  • Its not that important. I am gonna keep it that way ;). Thanks for all the help, really appreciate it. :) – cedzz Feb 01 '18 at 14:49