Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Custom Django Model Validation

I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What's the simplest way to implement this so that I don't have to repeat myself writing this logic?

e.g. I don't want to re-implement this logic in a Form and a ModelForm and an admin form and the model's overridden save().

As far as I know, Django doesn't make it easy to globally enforce these types of criteria.

Googling hasn't been very helpful, since "model validation" typically refers to validating specific model fields, and not the entire model contents, or relations between fields.

like image 254
Cerin Avatar asked Sep 09 '11 19:09

Cerin


People also ask

How can you validate Django model fields?

to_python() method of the models. Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)

How do I validate two fields in Django?

They go into a special “field” (called all), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error(). So from Django documentation you can use add_error() to do what you want to achieve.

How do I add a model field in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

What is validator in Django?

A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for re-using validation logic between different types of fields.

How do you validate a custom field in Django?

Custom Field Validations in Django Model are implemented when we create an instance of the model. Basically, the validation is implemented once we run ModelName.objects.create (data = data). The custom field validations in Django Model take a value and raises a ValidationError if it does not meet some criteria.

What are callable validators in Django?

The django.core.validators module contains a collection of callable validators for use with model and form fields. They’re used internally but are available for use with your own fields, too. They can be used in addition to, or in lieu of custom field.clean () methods. regex – If not None, overrides regex.

Do you need a custom model validator?

However, often we require further validations on some fields. Such as the title length or age can't be lesser than a particular value or the coupon code should be in all caps. In such scenarios building, a custom model validator is the most straightforward solution.

What does @validate_unique() method do in Django?

validate_unique implies [in it's method name] that you're validating a unique constraint. Django's "validating objects" documentation refers to the clean method.


1 Answers

The basic pattern I've found useful is to put all my custom validation in clean() and then simply call full_clean() (which calls clean() and a few other methods) from inside save(), e.g.:

class BaseModel(models.Model):          def clean(self, *args, **kwargs):         # add custom validation here         super().clean(*args, **kwargs)      def save(self, *args, **kwargs):         self.full_clean()         super().save(*args, **kwargs) 

This isn't done by default, as explained here, because it interferes with certain features, but those aren't a problem for my application.

like image 121
Cerin Avatar answered Sep 18 '22 05:09

Cerin