Display a boolean model field in a django form as a radio button rather than the default Checkbox

前端 未结 4 1920
猫巷女王i
猫巷女王i 2021-02-08 06:19

This is how I went about, to display a Boolean model field in the form as Radio buttons Yes and No.

choices = ( (1,\'Yes\'),
            (0,\'No\'),
          )
         


        
4条回答
  •  Happy的楠姐
    2021-02-08 06:48

    If you want to deal with boolean values instead of integer values then this is the way to do it.

    forms.TypedChoiceField(
        choices=((True, 'Yes'), (False, 'No')),
        widget=forms.RadioSelect,
        coerce=lambda x: x == 'True'
    )
    

提交回复
热议问题