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)
```python
class User(AbstractUser):
# ....
secondary_email = models.EmailField(null=True, blank=True)
```
## 3.
In this you can use validators from Django:
```python
from django.core.validators import MinValueValidator, MaxValueValidator
class Campus(Module):
# ...
lat = models.DecimalField(
max_digits=10,
decimal_places=6,
validators=[MinValueValidator(-85.05112878), MaxValueValidator(85.05112878)],
)
```
Or build your own ones. Some custom validators have been defined inside `backend/backend_app/validation/validators.py`. In particular, validation on `JSONField` is handled through the awesome standard [`json-schema`](https://json-schema.org/) 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):
```python
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.tag.name, self.content)
return super().save(*args, **kwargs)
class Meta:
abstract = True
```
In the associated serializer (in the `validate` function):
```python
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/models_serializers_viewsets.md)
* [Config files](Application/Backend/config_files.md)
* [Moderation & versioning](Application/Backend/moderation_and_versioning.md)
* [Data validation](Application/Backend/data_validation.md)
* [Tags](Application/Backend/tags.md)
* [API](Application/Backend/API.md)
* [Tests](Application/Backend/tests.md)
......
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