Reputation: 1139
I read the Django doc again and again but I keep struggling with the clean() method in modelforms.
Here is my models.py:
class Profile(models.Model):
number1 = models.IntegerField(blank=True, null=True)
number2 = models.IntegerField(blank=True, null=True)
class FormProfile(ModelForm):
def clean(self):
number1 = self.cleaned_data.get('number1')
number2 = self.cleaned_data.get('number2')
if number1 >= number2:
raise forms.ValidationError("number1 should not be above number2")
class Meta:
model = Profile
The clean() validation is done properly, but problem is that the basic validation of number1 and number2, which should be integers, does not raise any error anymore. For instance, if number1 is an integer but number2 is not an integer, then the cleaned_data dictionnary will only contain number1, which is normal since number2 was not validated, but no error is raised.
How can I make Django raise the basic errors first and then perform the clean() method only if no basic error is raised ?
Thanks !
Upvotes: 0
Views: 1111
Reputation: 43300
The basic validation you're talking about is invoked via the BaseForm
's clean
method, when you overrode this method, you hid the underlying validation.
You need to call the ModelForms base clean method via super in your clean method
def clean(self):
super(FormProfile, self).clean()
As shown in the example in the docs, you will still need to check if a value is none in your check so it would become
if number1 and number2 and number1 >= number2:
You could provide a default value with .get
but I wouldn't recommend it as it would make this check a little harder to verify correct results
Upvotes: 1
Reputation: 348
def clean(self):
# your validation
return super(FormProfile, self).clean()
Upvotes: 0