IordanouGiannis
IordanouGiannis

Reputation: 4357

How can I add choices to a timefield in a Django form?

In one of my models I have the following:

time = models.TimeField() 

In a modelform based on this model I want time to be a dropdown with a few choices, so I tried this:

time = forms.TimeField(label="time", choices=[(datetime.time(0, 0), "Midnight"), (datetime.time(12, 0), "Noon")])

I get the following error:

TypeError: __init__() got an unexpected keyword argument 'choices'

Do I have to put choices in my model's timefield or is there a way to be define it in the form ?

Upvotes: 3

Views: 3879

Answers (1)

MZA
MZA

Reputation: 1067

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)]

Upvotes: 6

Related Questions