[Django]-Django checking if an individual field has an error and not run clean()?

4πŸ‘

βœ…

If start_date and end_date are declared as blank=False, null=False (the default) then you can do something like this:

    def clean(self):

        cleaned_data = super(MyModelForm, self).clean()

        if not self.is_valid():
            return cleaned_data

        if cleaned_data.get('half_day'):
            if cleaned_data['start_date'] != cleaned_data['end_date']:
                self.add_error(
                    'half_day',
                    'Start and end date must be the same'    
                )

        return cleaned_data

The super clean will return the request back to the template with errors and you won’t have to deal with checking whether the fields have values.

πŸ‘€Rob L

Leave a comment