Django:BooleanField 返回“on”而不是 true?

Posted

技术标签:

【中文标题】Django:BooleanField 返回“on”而不是 true?【英文标题】:Django: BooleanField return 'on' instead of true? 【发布时间】:2020-09-12 03:58:24 【问题描述】:

我的随机化模型中有一个 BooleanField (ran_bug),它显示为一个复选框。 单击复选框将显示 2 个其他非必填字段(ran_dem_nom 和 ran_dem_dat)。

我的问题是,当我“选中”复选框时,它返回“on”而不是 true。

当我尝试注册数据时出现错误:

django.core.exceptions.ValidationError: ["'on' 值必须是 True、False 或 None。"]

models.py

class Randomisation(models.Model):

    ran_ide = models.AutoField(primary_key=True)
    pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country
    ran_str_num = models.CharField("Logical numerotation", max_length=2, null=True, blank=True)
    ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True)
    bra_lib = models.CharField("Arm label", max_length=50, null=True, blank=True)
    ran_act = models.IntegerField("Activated line", null=True, blank=True)
    pat = models.CharField("Patient number", max_length=12, unique=True, null=True, blank=True)
    ran_nai = models.IntegerField("Patient birthdate (year)", blank=True)    
    ran_sex = models.IntegerField("Sex", null=True, blank=True)
    ran_st1 = models.IntegerField("Stratification variable 1", blank=True)
    ran_st2 = models.IntegerField("Stratification variable 2", blank=True)
    ran_bug = models.BooleanField("Use of alternative randomization procedure?", null=True, blank=True)
    ran_dem_nom = models.CharField("Name of the person asking for randomization", max_length=12, null=True, blank=True) # hide at pageload
    ran_dem_dat = models.DateField("Date of demand", null=True, blank=True) # hide at pageload
    ran_log = models.CharField("User", max_length=12, null=True, blank=True)
    ran_dat = models.DateTimeField("Date", null=True, auto_now_add=True, blank=True)

forms.py

class RandomizationEditForm(forms.Form):

    def __init__(self, request, *args, **kwargs):
        super(RandomizationEditForm, self).__init__(*args, **kwargs)
        self.user_country = Pays.objects.get(pay_ide = request.session.get('user_country'))
        self.user_site_type = request.session.get('user_site_type')        
        PAYS = Pays.options_list(self.user_country,self.user_site_type,'fr')
        SEXE = Thesaurus.options_list(2,'fr')
        STRATE_1 = Thesaurus.options_list(3,'fr')
        STRATE_2 = Thesaurus.options_list(4,'fr')
        YES = [(None,''),(0,'Non'),(1,'Oui'),]

        self.fields["pay_ide"] = forms.IntegerField(label = "Pays", initial=2, widget=forms.HiddenInput())
        self.fields["pat"] = forms.CharField(label = "Numéro patient (XXX-0000)")
        self.fields['pat'].widget.attrs.update(
            'autocomplete': 'off'
        )
        self.fields["ran_nai"] = forms.IntegerField(label = "Date de naissance (année)", widget=forms.TextInput)
        self.fields['ran_nai'].widget.attrs.update(
            'autocomplete': 'off'
        )
        self.fields["ran_sex"] = forms.ChoiceField(label = "Sexe", widget=forms.Select, choices=SEXE)
        self.fields["ran_st1"] = forms.ChoiceField(label = "Gravité de la maladie COVID-19", widget=forms.Select, choices=STRATE_1)
        self.fields["ran_bug"] = forms.BooleanField(label = "Recours à la procédure de secours ?", required = False)
        self.fields["ran_dem_nom"] = forms.CharField(label = "Nom de la personne qui demande la randomisation", required = False)
        self.fields['ran_dem_nom'].widget.attrs.update(
            'autocomplete': 'off'
        )
        self.fields["ran_dem_dat"] = forms.DateField(
            # input_formats=settings.DATE_INPUT_FORMATS,
            label = "Date de la demande",
            initial = timezone.now(),
            required = False,
            )
        self.fields['ran_dem_dat'].widget.attrs.update(
            'autocomplete': 'off'
        )

JS

$(function()
        $("#div_id_ran_dem_nom").hide();
        $("#div_id_ran_dem_dat").hide();
    );

    // affichage des champs en fonction de la valeur sélectionnée dans la liste 
    $("#div_id_ran_bug").on("change", function(event)
        console.log($("#id_ran_bug").val())

        if ($("#id_ran_bug").is(":checked"))
            $("#div_id_ran_dem_nom").show();
            $("#div_id_ran_dem_dat").show();
        
        else 
            $("#div_id_ran_dem_nom").hide();
            $("#div_id_ran_dem_dat").hide();
        
    );

views.py

def randomization_edit(request):

    if request.method == "POST":
        form = RandomizationEditForm(request, data=request.POST or None)
        if form.is_valid():
            # Récupération des données permettant la randomisation 
            randomisation = Randomisation.objects.filter(Q(pay_ide=form.data.get('pay_ide')) & Q(ran_act=1) & Q(ran_st1=form.data.get('ran_st1')) & Q(pat=None)).first()

            randomisation.pat = form.data.get('pat')
            randomisation.ran_nai = form.data.get('ran_nai')
            randomisation.ran_sex = form.data.get('ran_sex')
            randomisation.ran_bug = form.data.get('ran_bug')
            randomisation.ran_dem_nom = form.data.get('ran_dem_nom')
            randomisation.ran_dem_dat = form.data.get('ran_dem_dat')
            print('ran_bug',form.data.get('ran_bug'))
            randomisation.ran_log = request.user.username
            randomisation.ran_dat = timezone.now()
            randomisation.save()

            return redirect('randomization:confirmation', pk = randomisation.pk)

    else:
        form = RandomizationEditForm(request)

    return render(request, 'randomization/edit.html', 'form': form)

【问题讨论】:

***.com/questions/23911602/… 谢谢。但是 form.data.get('ran_bug') 返回的值总是 'on' 而不是 'true' 或 'false' 您能发布引发异常的代码吗?观点还是什么?也许是完整的异常堆栈跟踪? 【参考方案1】:

好的,我解决了我的问题:form.cleaned_data['ran_bug'] 而不是 form.data.get('ran_bug')

【讨论】:

谢谢,这个答案让我明白了。然而,找到它并不是那么容易。我用谷歌:django form form get boolean "=on" true site:***.com

以上是关于Django:BooleanField 返回“on”而不是 true?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Django 上将 True 设置为 BooleanField 的默认值?

自定义包含 django.forms.CheckboxInput() 的 django.forms.BooleanField() 的样式

mysql 的 Django BooleanField 默认值

Django BooleanField 作为单选按钮?

django中关于BooleanField选项的字符串转化

Django model.BooleanField 值为 0/1