1

Django's ModelForms are cool, but I'm having trouble wrapping my head around why you'd ever want to put data integrity rules in your forms, when they could just be in the models themselves, per https://stackoverflow.com/a/18876223/1207253, who goes on to write "This isn't done by default, as explained here, because it interferes with certain features..."

I've read through the cited links and https://github.com/danielgatis/django-smart-save and still don't understand why this isn't the recommended approach. What are the features this approach interferes with? Excluded fields works. Default values works. What am I missing?

Community
  • 1
  • 1
  • Who says you should put data integrity rules in the form? You only need to call `.clean()` explicitly (for eg. if saving models from `manage.py shell` or in your custom views). If your models are saved / created from django admin, then you don't have to do anything extra at all. – Kedar Mar 07 '15 at 13:46
  • I dunno - just seems like all the docs point to doing validation in the form. So what's the downside of just having the model's save() clean() itself every time: http://stackoverflow.com/a/18876223/1207253? I understand if that's not the default behavior for backwards compatibility, but why doesn't everyone just follow this pattern then? – user3305798 Mar 07 '15 at 15:06

1 Answers1

1

Only downside I can think of is that full_clean or clean (whichever you call in save) will be called twice if saving models through admin. There shouldn't be any side effects as such.

Form validation puts restriction on how the user enters data, Model validation specifies how that data must be processed / validated further before storing it in the db. So, unless your forms are very complicated, validating in the model works just fine.

Use whichever you are most comfortable with and adhere to it throughout the project as there is no strong convention here.

Kedar
  • 1,648
  • 10
  • 20