Cansada de ser feliz

Bienvenidos a mi flujo de conciencia

How to show a BooleanField of a ModelForm as radio select (yes/no) in Django

| Comments

Let’s suppose that we have a field is_active in our model. It is a boolean field, but in a template we want to show it as a radio select.

In this case we just need to add choices attribute for the model field and then change a widget of the corresponding form:

forms.py
1
2
3
4
5
6
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'is_active': forms.RadioSelect
        }
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
from django.db import models

class MyModel(models.Model):
    STATE_CHOICES = (
        (True, u'Yes'),
        (False, u'No'),
    )
    is_active = models.BooleanField(
        verbose_name=u'Is it active?',
        default=False,
        choices=STATE_CHOICES,
    )

UPDATE:

For Django forms.

forms.py
1
2
3
4
5
6
7
8
from django import forms

class MyForm(forms.Form):
    is_active = forms.TypedChoiceField(
        coerce=lambda x: bool(int(x)),
        choices=((0, 'No'), (1, 'Yes')),
        widget=forms.RadioSelect
    )

Comments