9
3

More than 1 year has passed since last update.

django ModelFormクラスのwidget属性の使い方

Last updated at Posted at 2021-11-13

widget属性とは

djangoアプリにおいて、Formクラス, ModelFormクラスのフォーム部品の種類を規定する要素。

djangoフォームではフィールドを設定した時点でフォーム部品の種類が決まる(CharFieldであれば通常はinput type="text", choicesオプションがあればselect/option、など)が、このwidget属性を指定することである程度はフォーム部品のコントロールが可能。

SelectDateWidget

DateFieldに設定することで、年月日選択のプルダウンを生成できる。

DateTimeFieldにも設定可能だが、その場合であっても年月日欄のみが表示され時刻選択はできなくなる。

class ReservationForm(ModelFrom):
  class Meta:
  # 中略
  widgets = {
      "datetime": widgets.SelectDateWidget
    }

【widget設定前】
Image from Gyazo

【設定後】
Image from Gyazo

NumberInput(type="date")

HTMLのinput type="date"と同じ形式のカレンダーを生成する。

SelectDateWidgetと同じく、DateTimeFieldに対して使うと時刻が設定できなくなる。

class ReservationForm(ModelFrom):
  class Meta:
  # 中略
  widgets = {
    "datetime": NumberInput(attr={
      "type": "date"
    }
  }

NumberInputに対してattr属性を指定しないとただのinput要素になる。

Image from Gyazo

SpliteDateTimeWidget

日付用と時刻用の二つのinput要素を生成する。

上が日付で下が時刻
Image from Gyazo

このウィジェットを使う場合には、フォームのフィールドをSpliteDateTimeFieldに設定する必要がある。

forms.py
from django.forms import ModelForm, SplitDateTimeField, widgets
class ReservationForm(ModelForm):
  datetime = SpliteDateTimeField(label="予約日時")
  class Meta:
    fields = ["datetime"]
    widgets = {
      "datetime": widgets.SpliteDateTimeField
    }

上記の例だと日時を直接入力する必要がある。

DateFieldとは異なりSelectDateWidgetPNumberInput(type="date")のような便利なwidgetは用意されていないので、datepickertimeDropperなどのjqueryプラグインを用いることになる。

CheckboxSelectMultiple

複数選択可能なチェックボックスを生成する。

from django.forms import ModelForm, CheckBoxSelectMultiple
class TeamForm(ModelForm):
  class Meta:
    fields = ["users"]
    widgets = {
      "users": CheckboxSelectMultiple
    }
9
3
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
9
3