I want to create a shortcut method to raise ValidationError inside the Form.clean() method.
When we need to raise the same ValidationError (same message and same code) many times inside the Form.clean(), I should pass the same message every time.
Would be cleaner, pass only the error code and let the config Meta.error_messages solve them. Is there a way to solve this with Django:
What I want is something looks like the Serializer.fail() method of Django REST framework (docs
here).
This is a sample form with my suggestion:
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from .models import Variable
class VariableForm(forms.ModelForm):
def clean(self):
cleaned_data = super().clean()
type = cleaned_data.get('type')
value_bool = cleaned_data.get('value_bool')
value_str = cleaned_data.get('value_str')
value_num = cleaned_data.get('value_num')
if type == 'str' and (value_bool is not None or value_num is not None):
self.fail('incorrect_assignment', type='str')
if type == 'num' and (value_bool is not None or value_str is not None):
self.fail('incorrect_assignment', type='num')
if type == 'bool' and (value_num is not None or value_str is not None):
self.fail('incorrect_assignment', type='bool')
class Meta:
model = Variable
fields = ('name', 'type', 'value_bool', 'value_str', 'value_num')
error_messages = {
NON_FIELD_ERRORS: {
'incorrect_assignment': 'Incorrect assignment for variable of type %(type)s'
}
}
Without this shortcut I need raise a entire ValidationError (with message, code and parms arguments) three times with the same arguments except params. I can put the message inside a variable, but why not use the error_messages provided by the Django forms API?
Another problem is when I want to raise a required error programatically (inside the Form.clean() method) with the defaul message without pass them another time.