Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django BooleanField as a dropdown

Tags:

python

django

Is there a way to make a Django BooleanField a drop down in a form?

Right now it renders as a radio button. Is it possible to have a dropdown with options: 'Yes', 'No' ?

Currently my form definition for this field is:

attending = forms.BooleanField(required=True)
like image 634
John Smith Avatar asked Sep 08 '16 18:09

John Smith


3 Answers

What you can do is add "choices" key word to your BooleanField in your models.py

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

    attending = models.BooleanField(choices=BOOL_CHOICES)
like image 164
Thomas Turner Avatar answered Nov 05 '22 18:11

Thomas Turner


I believe a solution that can solve your problem is something along the lines of this:

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

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

Might not be exact but it should get you pointed in the right direction.

like image 30
Michael Platt Avatar answered Nov 05 '22 16:11

Michael Platt


With a modelform

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)
        }
like image 5
Lucas B Avatar answered Nov 05 '22 18:11

Lucas B