Commit da0c8905 authored by Florent Chehab's avatar Florent Chehab

Added doc on validation

parent 61bfd065
Pipeline #38479 passed with stages
in 3 minutes and 45 seconds
Data validation
Validation on data is performed at different levels:
1. Automatic validation from Django based on the fields of the models.
2. Automatic validation in the serializers based on the fields of the models.
3. Sometimes some extra (and/or custom) validators are added to enforce specific constraints on the field.
4. Sometimes some extra validation across multiple fields is added.
## 1. & 2.
Are enforced with no extra work (validators are deduced from the fields)
class User(AbstractUser):
# ....
secondary_email = models.EmailField(null=True, blank=True)
## 3.
In this you can use validators from Django:
from django.core.validators import MinValueValidator, MaxValueValidator
class Campus(Module):
# ...
lat = models.DecimalField(
validators=[MinValueValidator(-85.05112878), MaxValueValidator(85.05112878)],
Or build your own ones. Some custom validators have been defined inside `backend/backend_app/validation/`. In particular, validation on `JSONField` is handled through the awesome standard [`json-schema`]( and the associated package; you can look at the already defined schemas and validators to get inspired :smile:.
## 4.
In this case make sure to define the custom validation in both the serializer and model.
In a model (in the `save` function):
class TaggedItem(Module):
Abstract model to represent a tagged item
tag = models.ForeignKey(Tag, related_name="+", on_delete=models.PROTECT)
content = JSONField(default=dict)
def save(self, *args, **kwargs):
Custom save function to ensure consistency of the content with the tag.
validate_tagged_item(, self.content)
return super().save(*args, **kwargs)
class Meta:
abstract = True
In the associated serializer (in the `validate` function):
class TaggedItemSerializer(ModuleSerializer):
Serializer for tagged items
def validate(self, attrs):
attrs = super().validate(attrs)
validate_tagged_item(attrs["tag"].name, attrs["content"])
return attrs
......@@ -16,6 +16,7 @@
* [Models, Serializers and ViewSets](Application/Backend/
* [Config files](Application/Backend/
* [Moderation & versioning](Application/Backend/
* [Data validation](Application/Backend/
* [Tags](Application/Backend/
* [API](Application/Backend/
* [Tests](Application/Backend/
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment