Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#21590 closed Cleanup/optimization (invalid)

Don't require forms clean_* methods to return a value

Reported by: Aymeric Augustin Owned by: nobody
Component: Forms Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Adding custom validation to forms isn't as DRY as it colud be:

    class MyForm(forms.ModelForm):

        class Meta:
            model = MyModel

        def clean_title(self):
            title = self.cleaned_data["title"]
            validate_title(title)  # custom validation
            return title

        def clean_slug(self):
            slug = self.cleaned_data["slug"]
            validate_slug(slug)   # custom validation
            return slug

The requirement that clean() return a cleaned_data dict was recently lifted; what about doing the same for clean_*()? Then the example above could be simplified to:

    class MyForm(forms.ModelForm):

        class Meta:
            model = MyModel

        def clean_title(self):
            validate_title(self.cleaned_data["title"])  # custom validation

        def clean_slug(self):
            validate_slug(self.cleaned_data["slug"])   # custom validation

Otherwise developers go for private APIs, eg.:

    class MyForm(forms.ModelForm):

        class Meta:
            model = MyModel

        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            self.fields["title"].validators.append(validate_title)
            self.fields["slug"].validators.append(validate_slug)

Change History (3)

comment:1 by Simon Charette, 10 years ago

Maybe it was overlooked to allow clean_*() to return None?

comment:2 by Marc Tamlyn, 10 years ago

Resolution: invalid
Status: newclosed

We can't do this, as None is potentially a valid value for the field. It is conceivable for a field to have a non-None value beforehand, and a clean method to modify it to become None. In the case of clean(), this is not a problem as None is not a valid value for self.cleaned_data.

comment:3 by Aymeric Augustin, 10 years ago

I has a sad, but so be it...

Note: See TracTickets for help on using tickets.
Back to Top