1👍
class OrderForm(forms.ModelForm):
more_info = models.BooleanField(required=False)
def clean(self):
cleaned_data = super().clean()
if not cleaned_data['more_info']:
cleaned_data['details'] = ''
return cleaned_data
From Customizing validation:
This method [
clean()
] can return a completely different dictionary if it wishes, which will be used as thecleaned_data
.
Also:
-
CheckboxInput
is default widget forBooleanField
. -
If you want to include a boolean in your form that can be either
True
orFalse
(e.g. a checked or unchecked checkbox), you must remember to pass inrequired=False
when creating theBooleanField
.
0👍
Instead of updating cleaned_data
, try overriding the save
method instead
def save(self, force_insert=False, force_update=False, commit=True, *args, **kwargs):
order = super(OrderForm, self).save(commit=False)
if not self.cleaned_data.get('more_info', False):
order.details = ""
if commit:
order.save()
return order
Additionally, if you want to use the clean
method you need to call super’s clean first.
def clean(self):
cleaned_data = super(BailiffAddForm, self).clean()
if not cleaned_data.get('more_info', False):
...
return cleaned_data
- Reset form Django with instance
- Process to load database in django project
- Django membership/dashboard plugin
- Using querydict item for if-statement
Source:stackexchange.com