Reputation: 13315
I have a Django model and from.
class Settings(models.Model):
field_1 = models.BooleanField()
field_2 = models.CharField(max_length = 255)
and the form
class SiteSettingsForm(forms.ModelForm):
class Meta:
model = SiteSettings
I have an HTML form, and when the checkbox for the Boolean field_1
is not checked, then the 2nd field (field_2
) is disabled.
The problem is that, if I try and save the form, it says that there is an error, because field_2
is empty.
I want that, if the field_2
is not disabled and is not empty, to get the error but if field_2
is disabled, I want the form to take the value from the database.
I have tried this:
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
The problem is that I get an error:
This QueryDict instance is immutable
Upvotes: 1
Views: 610
Reputation: 3964
Change your form for it:
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
Upvotes: 2