Reputation: 781
I am trying to insert data into a NullBooleanField()
from a Django form, however, only 'True'
is ever added.
I have printed the cleaned data from 3 different fields from the form and it looks as follows:
True
False
None
(Which is what I would expect it to look like - as I selected 3 different options)
This is what the form fields look like:
MY_CHOICES = [(True, 'Yes'), (False, 'No'), (None, 'N/A')]
field_1 = forms.ChoiceField(
required=True,
choices=MY_CHOICES,
widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
label="Field 1"
)
And this is what the fields in the model looks like:
field_1 = models.NullBooleanField()
I don't understand why the data always inserts as 'True'
when I check in Django admin.
In Django admin, the choices are as follows: "Yes, No, Unknown"
So I have tried changing the form choices to read as follows:
MY_CHOICES = [('Yes', 'Yes'), ('No', 'No'), ('Unknown', 'N/A')]
But yet again, this does not work.
Can anyone suggest what might be the issue here?
EDIT -- Showing how this is saved to model
new_entry = ModelName(
field_1=form.cleaned_data['field_1'],
field_2=form.cleaned_data['field_2'],
field_3=form.cleaned_data['field_3'],
)
new_entry.save()
Upvotes: 0
Views: 325
Reputation: 781
Solution
Here is how to solve the issue.
forms.NullBooleanField(
widget=forms.RadioSelect(renderer=HorizontalRadioRendererSpace,
choices=CHOICES),
label='...',
required=False
)
NullBooleanField needs to be used when dealing with NullBooleanField in the model
Upvotes: 2