Reputation: 11
I have written my own validator as I have several fields in my form where the same validation is applicable and I wanted to reduce my code with clean_field() methods. My Form looks like this:
class EducationProjectAjaxForm(forms.Form):
study_fees_year_1 = forms.IntegerField(required=False, validators=[validate_study_fees])
study_fees_year_2 = forms.IntegerField(required=False, validators=[validate_study_fees])
study_fees_year_3 = forms.IntegerField(required=False, validators=[validate_study_fees])
study_fees_year_4 = forms.IntegerField(required=False, validators=[validate_study_fees])
My validator looks like this:
def validate_study_fees(data):
if data:
if data > 100000:
raise ValidationError(_('Falscher Wert: %(value)s'),
code='invalid',
params={
'value': 'Es sind maximal 100.000 € Studiengebühren pro Jahr erlaubt.'},
)
if data % 10 != 0:
raise ValidationError(_('Falscher Wert: %(value)s'),
code='invalid',
params={
'value': 'Der eingetragene Wert muss durch 10 teilbar sein.'},
)
if data < 0:
raise ValidationError(_('Falscher Wert: %(value)s'),
code='invalid',
params={'value': 'Der Finanzierungsbedarf darf nicht negativ sein'},
)
return data
My problem is that even though the validation itself is correctly applied I get the wrong error message: "Please choose a whole number". The message comes probably from the normal validation for IntegerFields but something like 123 throws the same message even though it is a whole number. If go the way with clean_study_fees_year_1(self), ... The error message is correctly shown. Is there something to fix my problem so I can have cleaner code? Thanks in Advance.
Django Version: 1.10
Upvotes: 1
Views: 961
Reputation: 309089
You should use unique error codes for your different error messages. If you use code='invalid'
, Django replaces your error message with the default message for the invalid code.
In addition, value
in the params should be the value you were validating, not an error message.
def validate_study_fees(data):
if data:
if data > 100000:
raise ValidationError(_('Es sind maximal 100.000 € Studiengebühren pro Jahr erlaubt.'),
code='too_large',
params={
'value': data},
)
if data % 10 != 0:
raise ValidationError(_('Der eingetragene Wert muss durch 10 teilbar sein.'),
code='not_divisible_by_10',
params={
'value': data},
)
if data < 0:
raise ValidationError(_('Der Finanzierungsbedarf darf nicht negativ sein'),
code='negative_value',
params={'value': data},
)
return data
See the docs on validators for more info.
Upvotes: 1