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 <https://www.django-rest-framework.org/api-guide/fields/#raising-validation-errors> ). 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. -- You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/4a526437-a0f5-4c37-bf7e-5868ff870bfd%40googlegroups.com.