My views.py file is quickly becoming large. Should I refactor it?
Eventually, every Django project reaches a state when you ask yourself: should I refactor this views.py file?
Maybe you find yourself jumping around randomly in a huge view.py file. Or it’s just the line count which seems larger than it should be. Are 500 lines too much? How about 2000?
Here are a few questions you can ask yourself to see if you should be worried, and a simple method to make large views.py files more manageable.
Is it really an issue already?
Refactoring should be motivated by an actual problem you’re experiencing. If you can navigate your views without issues, and your work isn’t negatively influenced, maybe you’re not doing anything wrong.
Being worried about line count should make you weary, but large files are not necessarily a bad thing. A huge file can help you spot underlying existing problems, which should be addressed.
Thin views and fat models
A large views.py file, might indicate that you’re doing too much in your views. Is there logic which would be better-off in your models, managers or forms?
If there are functions which are not views, you could extract them to a single file of helper functions, and import it in your views. Is there maybe even duplicated functionality which could be extracted out of your views?
A views submodule
Split your single views.py file up into multiple ones. Without having to change imports and urls in other places.
It’s pretty straightforward to transition from a single views.py towards a submodule.
First, you need to create a new directory next to your views.py file, called
Move your views.py file into it, and create an
views ├── __init__.py └── views.py
__init__.py file should have the following content:
from views import *
At this point, your application will work as expected, but you can begin splitting parts of the big views.py file into smaller parts.
If you have views, which are related to each other, you can add a new file called topic.py and move them there. The
views folder now looks like this:
views ├── __init__.py ├── topic.py └── views.py
Make sure your
__init__.py imports the content of topic.py, and you’re good to go!
from views import * from topic import *
This way, you can split a big views.py file into multiple ones by their topic, and will have an easier time navigating your views in the future, instead of having to scroll through a growing single views.py file.
Splitting files into modules in this fashion is a nice step, before you decide to create dedicated apps in your project.