How to split views.py into a directory (Django, Python)
Posted in General on July 24th, 2009 by slacy – 2 CommentsSo, I’ve been doing some Django programming on the side, and the thing that annoys me is that Django forces you to put nearly all your source code into 2 files: models.py and views.py
Being a reasonable person, I wanted to have a separate file for each view in my system. In other words, I want to create a views directory, with __init__.py inside, and my view files in there. Not being a Python expert, I found this harder than expected. Here’s what you need to do:
- Create a views directory.
- Split views.py into one file per method in the new views directory.
- Edit views/__init__.py and for each view, say “from myview import *”
- Use your views as you previously did in urls.py
I’ve heard some rumblings that you could create an __init__.py that did something like go through every file in the current directory and import everything there. That seems a bit over the top, and I’m happy to manage the imports in __init__.py for now.
I believe a very similar technique should work for Models, but I haven’t tested it.