Skip to content

Instantly share code, notes, and snippets.

@seLain
Last active March 6, 2018 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seLain/a09ba6df2be3f0b5798bb076a7d8adb1 to your computer and use it in GitHub Desktop.
Save seLain/a09ba6df2be3f0b5798bb076a7d8adb1 to your computer and use it in GitHub Desktop.
Django field validation before save
- 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