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

前端 未结 4 1914
猫巷女王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条回答
  • 2021-02-08 06:26

    Use TypedChoiceField.

    class EmailEditForm(forms.ModelForm):
        to_send_form = forms.TypedChoiceField(
                             choices=choices, widget=forms.RadioSelect, coerce=int
                        )
    
    0 讨论(0)
  • 2021-02-08 06:30

    Use this if you want the horizontal renderer.

    http://djangosnippets.org/snippets/1956/

    0 讨论(0)
  • 2021-02-08 06:43
    field = BooleanField(widget=RadioSelect(choices=YES_OR_NO), required=False)
    
    
    YES_OR_NO = (
        (True, 'Yes'),
        (False, 'No')
    )
    
    0 讨论(0)
  • 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'
    )
    
    0 讨论(0)
提交回复
热议问题