Djangocon: How to write a view - David Winterbottom
(One of the summaries of a talk at the
2015 Djangocon EU conference).
David Winterbottom says that on the one hand,
views are simple: a request comes in and a response goes out. On the other
hand, you have lots of freedom in views, which might lead to problems.
A central principle in software architecture is separation of
concerns. For instance by encapsulation: providing a clean interface and
hiding information from other parts of the system.
A well-known design pattern is MVC, model-view-controller. Originally used for
desktop application, but also used in most web frameworks. Note that every web
framework interpretes it differently.
- Model: business logic. Domain logic. The data, the rules.
- View: what the user sees.
- Controller: steers the whole process. The user interacts with the controller.
Django talks about MTV: model, template, view. He’d say that what’s the view
in MVC is mostly the templates and static files. The Controller in django is
then views, middleware, urls.py.
What David often notices in django projects is that the
views.py is too
big. There’s data validation in there. Some of the model layer creeps into the
view. And so on. You’re not encapsulating everything like you could be.
Django is for perfectionists with deadlines. With models and views you can
quickly get something working. But especially with the new class based views,
it is easy to mix the two up a bit, functionality-wise.
Perhaps it is caused by django’s convention of placing the database models in
models.py. There’s talk about “fat models, thin view” and the other way
around. That’s just shifting code between
Wouldn’t it be better to capture the domain knowledge in multiple files like
acl.py? Something like that might help
make your code cleaner and clearer.
Some “view smells”:
If your view start smelling, you have to know when to stop adjusting it and
when to just retreat back to a regular modelform, for instance.
What you should take away from this talk: keep views boring! Views should
be simple. The hard code should be in the domain layer. And: separate
What might help is asking yourself questions like:
- How would I do it if it were a REST API?
- How would I do this in a management command? (This question is great for
finding places where you’re wrongly passing a request around).