Django BooleanField as a drop down list

Is there a way to make Django BooleanField dropdown in form?

Right now, it appears as a switch. Is it possible to have a drop-down list with options: "Yes", "No"?

Currently, my form definition for this field is:

attending = forms.BooleanField(required=True)
+4
source share
3 answers

I believe that a solution that can solve your problem is something like this:

TRUE_FALSE_CHOICES = (
    (True, 'Yes'),
    (False, 'No')
)

boolfield = forms.ChoiceField(choices = TRUE_FALSE_CHOICES, label="Some Label", 
                              initial='', widget=forms.Select(), required=True)

You may not be accurate, but that should make you point in the right direction.

+9
source

What you can do is add the keyword "choice" to your BooleanField in your models.py

class MyModel(models.Model):
    BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))

    attending = models.BooleanField(choices=BOOL_CHOICES)
+6
source

TRUE_FALSE_CHOICES = (
    (True, 'Yes'),
    (False, 'No')
)
class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('attending',)
        widgets = {
            'attending': forms.Select(choices=TRUE_FALSE_CHOICES)
        }
0

Source: https://habr.com/ru/post/1654052/


All Articles