Django: Fat Views

Apr 18, 2016 21:07 · 206 words · 1 minute read django python views code-smells

Personally I like Class Based Views. They help me keep my file short and free of logic. Granted, they are slightly unwieldy at first and do have a steeper learning curve than Function Based Views, but once you’ve learnt a few you’re most the way there. If you find the docs confusing check out CCBV for a better reference.

Oftentimes I come across views that are simply doing too much. Views should be the glue that joins forms and models together with the request. Ask yourself:

  • Am I doing any data processing to get it ready to save? Move it to the form.
  • Am I doing anything with the ORM?
  • Can I use a class based view?

Your views shouldn’t be doing anything on behalf of another component. If it is then move the functionality to the correct component.

Yet sometimes your code just doesn’t really belong in any of the Django components. For example, if you are doing anything complex then do not be scared to break out of the Django world and create a standard Python package. This has the added benefit of decoupling your complex logic from Django, it can be treated as its own entity and interacted like any other library.