Reputation: 643
I wrote a custom validator, which will raise ValidationError if given field value is negative.
def validate_positive(value):
if value < 0:
raise ValidationError(
_('%(value) is negative number'),
params = {'value': value}
)
i added this to my model field via the field’s validators argument
class Book(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=50)
price = models.IntegerField(default=0,validators=[validate_positive])
quantity = models.IntegerField(default=0,validators=[validate_positive])
But while creating object it's not raising any error if price is less than zero.
I don't know where i am doing wrong and i am new to django.
I am using Django 1.9.
Please help me .
Upvotes: 2
Views: 2412
Reputation: 46
I ran into the same issue. So the validators only work when you are using Forms and Model Form to fill it.
You can validate the validators in the shell though.
python manage.py shell
>>>from app.models import Book
>>>Book.price.field.run_validators(value=<undesirable value>)
This would raise a validation error so you can be sure your validation is working.
Upvotes: 2
Reputation: 43300
Validators are used for forms, not for creating an object. If you're creating an object outside of a form then you need to provide an alternative way to validate input.
The easiest way to do this is to call the model's full_clean
method before saving as shown in the docs
from django.core.exceptions import ValidationError
try:
article.full_clean()
except ValidationError as e:
# Do something based on the errors contained in e.message_dict.
# Display them to a user, or handle them programmatically.
pass
This is similar to what would happen from a form, and would call any validators on your model fields.
Upvotes: 7