Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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???

like image 429
nsbm Avatar asked Dec 06 '22 12:12

nsbm


1 Answers

I know this has been answered for a while now, but I was also trying to solve this problem and came across this question.

After trying emyller's solution, it seemed to work, however when I looked at the form's self.cleaned_data, I saw that the values I got back were all either True or None, no False values were recorded.

I looked into the Django code and saw that while the normal NullBooleanField select does indeed map None, True, False to 1, 2, 3 respectively, the RadioSelect maps 1 to True, 0 to False and any other value to None

This is what I ended up using:

my_radio_select = forms.NullBooleanField(
    required=False,
    widget=widgets.RadioSelect(choices=[(1, 'Yes'), (0, 'No'), (2, 'N/A')]),
    initial=2,  # Set initial to 'N/A'
)
like image 176
Villiers Strauss Avatar answered Jan 18 '23 00:01

Villiers Strauss