{{{
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)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/21590>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
Comment (by charettes):
Maybe it was overlooked to allow `clean_*()` to return `None`?
--
Ticket URL: <https://code.djangoproject.com/ticket/21590#comment:1>
* status: new => closed
* resolution: => invalid
Comment:
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`.
--
Ticket URL: <https://code.djangoproject.com/ticket/21590#comment:2>
Comment (by aaugustin):
I has a sad, but so be it...
--
Ticket URL: <https://code.djangoproject.com/ticket/21590#comment:3>