Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider discussing about Validation Data strategies #24

Open
ddahan opened this issue Apr 22, 2017 · 0 comments
Open

Consider discussing about Validation Data strategies #24

ddahan opened this issue Apr 22, 2017 · 0 comments

Comments

@ddahan
Copy link

ddahan commented Apr 22, 2017

Location within the Book

  • Chapter or Appendix: 11.1: Validate All Incoming Data With Django Forms

Description

While the book already explains well how to validate models with ModelForm class in this section, some may prefer using validation at a model level (with validators in field declaration and/or overriding clean/clean_field methods in model).

To my view, setting validation at this lower level can decrease the risk of inserting bad data in database, especially when a project has many sources of input data, because you could forget to call the validation process.

In the case of you choose model-level validation, it could be well to warn people about the strange Django behaviour in which a call to the save method does not trigger the model validation, because the full_clean method is actually not called, for backward-compatibility purposes. I personally find this behaviour very counter-intuitive.

For this purpose, the mixin bellow is often used:

class ValidateOnSaveMixin(object):

    def save(self, force_insert=False, force_update=False, **kwargs):
        if not (force_insert or force_update):
            self.full_clean()
        super(ValidateOnSaveMixin, self).save(force_insert, force_update, **kwargs)

The problem and different solutions are well explained here: https://www.xormedia.com/django-model-validation-on-save/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant