Last active
March 6, 2018 07:20
-
-
Save seLain/a09ba6df2be3f0b5798bb076a7d8adb1 to your computer and use it in GitHub Desktop.
Django field validation before save
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Django does not automatically check max_lenght limitation before save() | |
- Django does not automatically check choices before save() --> it's for form | |
for the length limitation, using | |
datamodel.full_clean() | |
datamodel.save() | |
can resolve it. or, override save() to enforce full_clean() | |
ex: | |
```python | |
def save(self, force_insert=False, force_update=False): | |
self.full_clean() | |
models.Model.save(self, force_insert, force_update) | |
``` | |
for the choices validation issue, override save() to enforce validation of specific field to match choices. | |
ex: | |
```python | |
def save(self, force_insert=False, force_update=False, *args, **kwargs): | |
valid_categories = [v[0] for v in InformationDislike.DISLIKECHOICE] | |
if self.category not in valid_categories: | |
raise IntegrityError("Invalid value %s for category field. The available values are %s"\ | |
% (self.category, valid_categories)) | |
models.Model.save(self, force_insert, force_update, *args, **kwargs) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment