如何临时传递表单字段的表单验证

时间:2017-03-13 20:33:32

标签: python django django-models django-forms

我有以下型号:

class Regulatory(models.Model):  
    field1 = models.BooleanField(choices=BOOL_CHOICES, default=None, )
    field2 = models.IntegerField(choices=THREE_CHOICES, default=None,)

我有以下表格:

class RegulatoryForm(forms.ModelForm):

    field1 = forms.BooleanField(required=False)
    field2 = forms.IntegerField(required=False)


    class Meta:
        model = Regulatory
        widgets = {
                   'field1': forms.RadioSelect(attrs={"required": "required"}), 
                   'field2': forms.RadioSelect(attrs={"required": "required"}), 
       }

     def __init__(self, *args, **kwargs):
        self.site_id = kwargs.pop('site_id', None)
        super(RegulatoryForm, self).__init__(*args, **kwargs)

     def clean(self):
        data = self.cleaned_data
        if self.site_id == 2:
            data['field1'] = 0
            data['field2'] = 0
        else:
            return data

当我提交表单时,仍然会收到验证错误:

  

字段错误:此字段不能为空。

如何允许所需字段暂时传递到我的视图,以便在保存之前设置它们?

1 个答案:

答案 0 :(得分:0)

我添加了空白=真,我参加了比赛。