Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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を使っています。 

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away