How to split views.py into a directory (Django, Python)

So, 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:

  1. Create a views directory.
  2. Split views.py into one file per method in the new views directory.
  3. Edit views/__init__.py and for each view, say “from myview import *”
  4. 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.

  1. The content of my __init__.py for a directory where I want to import all of the files looks like:

    names = [f[:-3] for f in os.listdir(__path__[0]) if (not f.startswith(‘_’)) and f.endswith(‘.py’)]
    __all__ = []
    for name in names:
    exec(“from %s import *” % name)
    exec(“import %s” % name)
    exec(“__all__.extend(%s.__all__)” % name)

    (Those last three exec lines are all indented one level).

    You could possibly remove the references to __all__, but I leave them in, and then in each file, only add the classes/functions I wan exported to __all__ in each of them.

  2. Rushabh says:

    I started writing a comment and it got big enough to warrant its own post:
    http://radoshi.blogspot.com/2009/07/geek-splitting-django-views.html

    I don’t think hacking __init__ is a good idea, I’d rather hack the urls.py to point to the right thing.

    Note that models should be *significantly* easier, because models is meant to be split and I don’t think there are functions which expect the models.py to contain everything (other than admin views if you are using that).

  1. There are no trackbacks for this post yet.

Leave a Reply