[Fixed]-Django model forms cant change field value in clean()

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 the cleaned_data.

Also:

  1. CheckboxInput is default widget for BooleanField.

  2. BooleanField note:

    If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.

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

Leave a comment