1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Django】formsファイルで動的なフォームを作成(__init__関数の使い方)

Posted at

ポイント

formsファイルで動的なフォームを定義するときは__init__関数を使いなさいよという話。
formsファイルは基本的にシステムを起動した最初の一度だけしか実行されないが、__init__だけは毎度実行されるため、動的な処理はこの中に書かないといけない。

例1:動的な選択肢を持つChoiceField

forms.py
class SelectForm(Form):
    select_sample = ChoiceField(
        widget=Select()
    )

    def __init__(self, *args, **kwargs):    
        super().__init__(*args, **kwargs)

        # ここで選択肢となるsample_choicesを作成...

        self.fields['select_sample'].choices = sample_choices

例2:viewsからの値取得

もし任意の値をviewsからformsに渡したいときはkwargsを使う

views.py
# フォームを定義する時に値を渡す
form = SelectForm(sample_text=sample_text)
forms.py
class SelectForm(Form):
    select_sample = ChoiceField(
        widget=Select()
    )

    def __init__(self, *args, **kwargs):
        self.sample_text = kwargs.pop('sample_text') # この行を追加
        super().__init__(*args, **kwargs)

        # ここで選択肢となるsample_choicesを作成...

        self.fields['select_sample'].choices = sample_choices
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?