LoginSignup
5
5

More than 5 years have passed since last update.

djangoのFormのChoiceFieldにselectedを入れたい

Posted at

<select>にselectedを入れたい時に悩んだ。

<select name="breakfast">
    <option value="hamu">hamu</option>
    <option value="egg" selected="selected">egg</option>
    <option value="milk">milk</option>
</select>

こんなの使いたい時にform.pyとかに

from.py
breakfast = forms.ChoiceField(label='朝ごはん',
                              widget=forms.Select,
                              choices=Family.FOOD_CHOICES,)

として、templateに渡す前にinitialにフィールド名と指定したい値を設定します。

xxx_form['initial'] = {'breakfast':'egg'}

なんということでしょう!templateはこれだけでイチバン上のHTMLが出力されました。

{{ xxx_form.breakfast }}
5
5
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
5
5