LoginSignup
4
4

More than 5 years have passed since last update.

Django1.8からはforms.ChoiceFieldのchoices属性にcallableオブジェクトが渡せて地味便利

Posted at

Django1.8から、forms.ChoiceFieldのchoices属性にcallableオブジェクトが渡せるようになりました。
フォームの選択肢を動的に求めたい時に地味に便利です。

以下の例では、現在日時から1時間おきに10件分の選択肢を選べるようにしています。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)
        ),
    )

この書き方にしておくと、ブラウザをリロードするたびに選択肢が変化します。

参考URL: Form fields | Django documentation | Django


  1. python-dateutilを使っています。 

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4