Assuming I have a Django model like the following:
class Comprobante(models.Model):
punto_venta = models.IntegerField(blank=True)
And I want to validate the model and particularly that punto_venta
it is a value from 1 to 9999. I understand that there are two ways:
Use a validator in the field
def punto_venta_validate(value):
if not value:
raise ValidationError(_('El punto de venta es obligatorio'))
if value <1 or value > 9999:
raise ValidationError(_('El punto de venta debe debe ser un valor entre 1 y 9999'))
class Comprobante(models.Model):
punto_venta = models.IntegerField(blank=True, validators=[punto_venta_validate]))
Validate on clean()
model event
def clean(self):
punto_venta_validate(self.punto_venta)
The only visible difference is that a ValidationError
when the field is validated by using validators
, it will show the message next to the field in the admin interface, when we use clean()
to validate, I see that the error appears on all the fields. Eventually clean()
, we could also validate multiple conditions and add each error to a list, in this way we could show all the errors of each field, so there would not be a difference between the two methods either. So: What is the difference between both methods? Is it just a matter of how they are displayed ValidationError
or is there something else that I am missing?
Indeed as I mentioned in the comment:
The
validadores
only validate the input, they do not return the enhanced format, that is, it cannot be modified. If the input is invalid, it will just output aValidationError
.The methods
Clean()
validate and return a value that could be a slightly modified value depending on the requirements.Django will first run the built-in field validators (by default), then your custom field validators (using
validators=[su_validador]
in your models).clean()
So, Django will execute the and methodsclean<campo>()
.I think one of the main difference between methods
validator
and aclean_<campo>()
is that the latter is only intended for forms. And thevalidator
can be used for both your forms and your models (and will therefore also be used, for example, in the admin interface).Also, overriding the method
clean_<campo>()
is the recommended way to validate data against items in your database.Note: You can also apply the same validator to your form fields if you only want it there and not throughout your application.