Everybody knows that you shouldn’t put too much logic into your views. Doing so inevitably makes debugging harder, makes testing _much _harder, and reduces both the reusability and refactoring factor (TM) of your code.
So what should you do instead? The usual answer is “fat models” although there’s a strong argument for fat managers, querysets, and forms (which can be elegantly combined). But first, how do you know how much logic in your view really belongs there? I don’t have a one-size fits all answer, but I do have a heuristic: try turning your view into a management command.
Okay, you don’t _really _need to turn it into a management command, but at least work through the mental exercise of what it would take. This is an application of the hexagonal architecture and my thesis that management commands are just views for the command line. Instead of URL arguments, you supply command line arguments and options, instead of an HTTP request you can provide either the command itself or additional file information, and so on and so on. It’s a simplification, obviously, but it works - I promise!
Putting aside the logic for selecting objects, rendering responses, etc., how much would you have to duplicate in the management command? If it’s more than a few lines then there’s a pretty good chance there’s too much logic in the view itself. Start by identifying what makes sense to include in your model classes, where it makes sense to push logic to managers or form classes, or even separate functions. Let your views be HTTP interfaces to the application logic, not the application itself.
Until the next issue,
Ben, Co-founder & Chief Djangonaut
Learn from more articles like this how to make the most out of your existing Django site.