Starting with Django1.8, you can pass a callable object to the choices attribute of forms.ChoiceField. This is convenient when you want to dynamically ask for form choices.
In the example below, you can select 10 options every hour from the current date and time. [^ 1]
forms.py
# -*- coding: utf-8 -*-
from django import forms
from dateutil import rrule
from datetime import datetime
class ExampleForm(forms.Form):
start_at = forms.ChoiceField(
choices=lambda: (
(str(t), t.strftime('%H:%M:%S'))
for t in rrule.rrule(rrule.HOURLY, dtstart=datetime.now(), count=10)
),
)
This way you'll have different choices each time you reload your browser.
Reference URL: Form fields | Django documentation | Django
[^ 1]: I'm using python-dateutil.
Recommended Posts