[Django]-Django best practices – where should form processing logic (for creating / updating models) go

4👍

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.

👤Matt

Leave a comment