2
2

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 5 years have passed since last update.

Django の BooleanField に 0,1 を指定してチェックを付けたい

Last updated at Posted at 2019-10-24

真偽値を 0,1 で管理してる環境で引っかかりやすい

環境

  • Django 2.2
  • Python 3.6.8

事象

python は 0 = False と判断してくれるので
BooleanField の初期値に 0 or 1 を指定すれば正しく動作する事を期待してしまう

forms.py
class SampleForm(forms.Form):
    check_1 = forms.BooleanField(initial=1)
    check_0 = forms.BooleanField(initial=0)

実際は 0 の場合にもチェックが付いてしまう。

image.png

原因

チェックボックスの判定は↓の boolean_check メソッドで判定される。

widgets.py
def boolean_check(v):
    return not (v is False or v is None or v == '')

数値は考慮されていないので、0 だろうが 1 だろうが v is None の部分で必ず True と判定される

対応

check_test は引数で変更が可能なので、 数値を考慮した判定メソッドを指定すると

forms.py
# このメソッドを自作する
def wrap_boolean_check(v):
    return not (v is False or v is None or v == '' or v == 0)


class SampleForm(forms.Form):
    check_1 = forms.BooleanField(
        initial=1,
        widget=forms.CheckboxInput(check_test=wrap_boolean_check)
    )
    check_0 = forms.BooleanField(
        initial=0,
        widget=forms.CheckboxInput(check_test=wrap_boolean_check)
    )

想定通りに動作してくれる。

image.png

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?