django modelform validation如果没有表单,则从db获取字段

时间:2012-05-13 13:57:22

标签: python django validation django-forms

我有一个Django模型,来自。

class Settings(models.Model):
    field_1 = models.BooleanField()
    field_2 = models.CharField(max_length = 255)

和表格

class SiteSettingsForm(forms.ModelForm):
    class Meta:
        model = SiteSettings

我有一个HTML表单,当没有选中布尔field_1的复选框时,第二个字段(field_2)被禁用。

问题在于,如果我尝试保存表单,则表示存在错误,因为field_2为空。

我希望如果field_2未被禁用且不为空,则获取错误但如果field_2被禁用,我希望表单从数据库中获取值。

我试过这个:

class SettingsForm(forms.ModelForm):
    class Meta:
        model = Settings

    def __init__(self, *args, **kwargs):
        super(SettingsForm, self).__init__(*args, **kwargs)

    def clean(self):
        field_1 = self.data.get('field_1','')
        if not field_1:   # field_2 is disabled 
            self.data['field_2'] = self.instance.field_2 # so get from db
        super(SettingsForm, self).clean()
        return self.cleaned_data

问题是我收到错误:

  

此QueryDict实例是不可变的

1 个答案:

答案 0 :(得分:2)

更改您的表单:

class SettingsForm(forms.ModelForm):
    class Meta:
        model = Settings

    def __init__(self, *args, **kwargs):
        super(SettingsForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(SettingsForm, self).clean()
        field_1 = cleaned_data.get('field_1','')
        if not field_1:   # field_2 is disabled 
            cleaned_data['field_2'] = self.instance.field_2 # so get from db
        self.cleaned_data = cleaned_data
        return self.cleaned_data