6👍
Model:
import datetime as dt
begin_time = models.TimeField(default=dt.time(00, 00))
Form:
import datetime as dt
HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(0, 24)]
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
widgets = {'begin_time': forms.Select(choices=HOUR_CHOICES)}
and that’s it really. The result is a pull down for the users showing the 24 hours (so no messing with input fields and users entering all sorts of silly stuff) and the result is a TimeField straight into the database.
Extra: if None is allowed change the model to:
begin_time = models.TimeField(null=True, blank=True)
and the choice list:
HOUR_CHOICES = [(None, '------')] + [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(0, 24)]
👤MZA
Source:stackexchange.com