1

我有一个 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 实例是不可变的

4

1 回答 1

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
于 2012-05-13T14:32:04.057 回答