I have the following custom validation for a combination of fields I use throughout my site:
class MyModelForm(forms.ModelForm):
my_field_type_constant = 'my_field_type'
my_field_code_constant = 'my_field_code'
class Meta:
model = MyModel
def validate_my_field_code(self, my_field_code_error, my_field_type, my_field_code):
validate = URLValidator(verify_exists=False)
try:
validate(my_field_code)
except ValidationError:
messsge = u"My custom error"
self._errors[my_field_code_error] = self.error_class([messsge])
def clean(self):
cleaned_data = super(MyModelForm, self).clean()
my_field_type = cleaned_data.get(self.my_field_type_constant)
my_field_code = cleaned_data.get(self.my_field_code_constant)
my_field_type_from_model = other_model.models.my_field_TYPES[1][0]
if my_field_type == my_field_type_from_model:
self.validate_my_field_code(self.my_field_code_constant, my_field_type, my_field_code)
return cleaned_data
I use the combination of my_field_type and my_field_code in many of the forms in my site. I want to adhere to the DRY principle. How do I make the validation for these fields available to other forms without copying and pasting it into all the other forms?
Why not just subclass your other ModelForm classes that will use this validation:
class MyOtherModelForm(MyModelForm):
pass
Then you get it all for free though inheritance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments