Search code examples
pythondjangoformsform-fields

Django: Display NullBooleanField as Radio and default to None


I am successfully implementing NullBooleanField as radio buttons in several ways but the problem is that I can not set the default value to None.

Here is the code:

models.py:
class ClinicalData(models.Model):
      approved = models.NullBooleanField()
      ...

forms.py:
NA_YES_NO = ((None, 'N/A'), (True, 'Yes'), (False, 'No'))
class ClinicalDataForm(ModelForm):
      approved = forms.BooleanField(widget=forms.RadioSelect(choices=NA_YES_NO))
      class Meta:
           model = ClinicalData 

I tried the following methods: Set default:None in the model and/or setting inital:None in the form and also in the view in the form instance.
None of that was successfull. Im currently using CharField instead of NullBooleanField.
But is there some way to get this results with NullBooleanField???


Solution

  • For some odd reason - I didn't check it at the Django code -, as soon as you provide a custom widget for a NullBooleanField, it doesn't accept the values you expect (None, True or False) anymore.

    By analyzing the built-in choices attribute, I found out that those values are equal to, respectively, 1, 2 and 3.

    So, this is the quick-and-dirty solution I fould to stick to radio buttons with 'Unknown' as default:

    class ClinicalDataForm(forms.ModelForm):
        class Meta:
            model = ClinicalData
    
        def __init__(self, *args, **kwargs):
            super(ClinicalDataForm, self).__init__(*args, **kwargs)
            approved = self.fields['approved']
            approved.widget = forms.RadioSelect(
                choices=approved.widget.choices)
            approved.initial = '1'
    

    It doesn't look good and I wouldn't use it unless very necessary. But there it is, just in case.