Choices Yes/No for Boolean Field in Django
Aug. 18, 2022
django
Sometimes you need to represent boolean field of the Django model as dropdown list choices, like “Yes/No” instead default boolean field form widget - CheckboxInput. You can implement it like this.
class Post(models.Model):
IS_PUBLISHED_CHOICES = [(False, 'No'), (True, 'Yes')]
...
is_published = models.BooleanField("Published?", default=False,
choices=IS_PUBLISHED_CHOICES)
And ModelForm example
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['is_published', ]
widgets = {
"is_published": widgets.Select(attrs={
'class': 'form-control',
}),
}