简体   繁体   English

django modelform显示现有实例

[英]django modelform showing an existing instance

I have the following model: 我有以下模型:

ynChoice = ((None, 'Acknowledgement not required'),
            (True, 'Acknowledgement and consent required'),
            (False, 'Acknowledgement required but consent not required'))

class AbstractForm(models.Model):
    """base class for the below 2 classes"""
    #require users to say yes and no other than acknowledging #null = not required
    yes_no_required = models.NullBooleanField(choices=ynChoice, blank=False)

and I map it to my modelform: 然后将其映射到我的模型:

class LiveConsentForm(forms.ModelForm):
    ynChoice = (
                ('', '---------------'),
                (None, 'Acknowledgement not required'),
                (True, 'Acknowledgement and consent required'),
                (False, 'Acknowledgement required but consent not required'),
                )
    yes_no_required = forms.TypedChoiceField(choices=ynChoice,empty_value='')
    class Meta:
        model = ConsentFormTemplate

Here, ConsentFormTemplate is a subclass of AbstractForm . 在这里, ConsentFormTemplateAbstractForm的子类。 I wrote yes_no_required in the form because the empty value for the nullbooleanfield's formfield will return a None , which I do not want. 我写yes_no_required的形式,因为对于nullbooleanfield的formfield空值将返回一个None ,这是我不想要的。

Now, when I want instantiate my form to show an existing record, LiveConsentForm(instance=templateInstance) , I run into a problem. 现在,当我想实例化表单以显示现有记录LiveConsentForm(instance=templateInstance) ,我遇到了问题。

My templateInstance.yes_no_required 's value is None, but when the html is rendered, ------ is selected. 我的templateInstance.yes_no_required的值为None,但是在呈现html时,选择了------ (I do not have such trouble when yes_no_required is either True or False ) (当yes_no_requiredTrueFalse时,我没有这种麻烦)

Need some help here. 在这里需要一些帮助。

ok i've looked at the forms.fields and 好的,我已经看过forms.fields和

turns out that when rendering to html, turns out that None is just treated as '', and empty_value is not taken into consideration here. 事实证明,当渲染为html时,结果将None仅仅视为'',并且在这里不考虑empty_value。 I'm not sure why @Ignacio Vazquez-Abrams dude took away his answer, so if you can please put it back up again, i'll accept it. 我不知道为什么@Ignacio巴斯克斯 - 艾布拉姆斯的家伙拿走了他的答案,所以如果可以请你把它放回去再升,我会接受它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM