Django:显示NullBooleanField为Radio,默认为None [英] Django: Display NullBooleanField as Radio and default to None
问题描述
我以几种方式成功实现了 NullBooleanField
作为单选按钮,但问题是我无法将默认值设置为无。
这里是代码:
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
我尝试了以下方法:
在模型和/或设置中设置
在表单中,也在表单实例的视图中。 默认值:无
inital:无
没有一个是成功的。 Im目前使用 CharField
而不是 NullBooleanField
。
但是有一些方法可以用 NullBooleanField
???
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
???
推荐答案
由于某些奇怪的原因 - 我没有在Django代码中检查它,只要您为NullBooleanField提供自定义窗口小部件,它不接受您期望的值(无
, True
或 False
)
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.
通过分析内置的选择属性,我发现这些值分别等于 1
, 2
和 3
。
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.
这篇关于Django:显示NullBooleanField为Radio,默认为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!