Reputation: 51
I have problems with the parameters, when The validator is written used this way:
cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias])
It automatically gets the value of the respective field in the validator.py
def insumo_existencias(value):
#Por alguna razon, me esta devolviendo un string
insumo = models.Insumo.objects.get(id=1)
if (insumo.cantidadexistencias < value):
raise ValidationError(
_('Error no hay existencias suficientes'),
)
So, I just have to call it value and that´s it, but when I want to pass another parameter,the function does not longer get the value of the field. I tried this:
cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias(cantidadusada,idinsumo)])
It is not working. Obviosuly the validator function was changed to acept to parameters
Upvotes: 1
Views: 770
Reputation: 1
you can pass multiple parameters to a validator by creating a custom validator function or class.
Using a Function
from django.core.exceptions import ValidationError
def custom_validator(value, param1, param2):
if not some_condition(value, param1, param2):
raise ValidationError(f'{value} failed the validation with {param1} and {param2}')
Since Django validators only accept a single argument (value
), you need to use a lambda or a partial function to pass additional parameters:
from functools import partial
class MyModel(models.Model):
my_field = models.CharField(max_length=100, validators=[partial(custom_validator, param1='value1', param2='value2')])
but using the save function of the class is going to let you do some logic before saving it to the database
Upvotes: 0
Reputation: 1
You can change it in save function:
def save(self,*args, **kwargs):
if (insumo.cantidadexistencias > value):
super().save(*args, **kwargs)
else:
pass
#do not save it!and raise error
Upvotes: 0