[PYTHON] From Django 1.8, you can pass a callable object to the choices attribute of forms.ChoiceField, which is very convenient.

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

From Django 1.8, you can pass a callable object to the choices attribute of forms.ChoiceField, which is very convenient.
[Python] You can save an object to a file by using the pickle module.
The wall of changing the Django service from Python 2.7 to Python 3
A Python script that allows you to check the status of the server from your browser
The story of a Django model field disappearing from a class
Django Make choices only for the facility you belong to
Is there a secret to the frequency of pi numbers?
[Django] What to do if the model you want to create has a large number of fields
Django shift table Shows only the facilities to which you belong
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
[AtCoder for beginners] A story about the amount of calculation that you want to know very roughly