Reputation: 11921
I am trying to make my Django app follow better practices than it currently does. I hear about fat models and thin controllers a lot (after putting much of my display logic in views.py
initially).
Anyway, say I have a moderately complex form, for creating new objects, including foreign keys on the new objects. Assuming there are no validation errors, where should the logic for creating / linking models go? views.py
after is_valid()
seems the easiest place to put, but I am not sure if that is considered best practice.
Upvotes: 3
Views: 885
Reputation: 2821
In the question title you describe it as "form processing logic", but it sounds from your question text like you really mean inter-model business logic.
If it's form processing logic (cleaning, etc.), that should go on the form.
Since it sounds like you're talking about business logic, it should generally be added to the appropriate model as a model method (Django docs on model methods), then called from either the custom form logic (e.g., on save
) or from the view.
Of course, where the code lives depends to a great degree on the structure of relationship between your models. Say you have an author model with a one-to-many relationship to a book model. The author model might have a method that helps you create a new book object, filling in the foreign key relation as it goes. A more complex relationship might require more view code, or at least more thought.
And yes, in general it's a good idea to try to keep your views slimmer and your models fatter.
Upvotes: 4