Separating Django Views.py

February 4, 2011

I have a reasonable sized Django application, and I'm building a mobile version. Rather than run a completely different Django instance (and therefore a separate gunicorn process) I'm building it as an app inside the main site, running on a /mobile/ offset.

The mobile version has several different areas of functionality, but is still fairly simple. I'd therefore like to split up views.py into separate files to make it easier to maintain.

To do this, create a views directory inside your app, in the same place as views.py. Put an init file in here to turn it into a python package.

Inside here, create a separate .py file for each of the areas you want. I ended up with bands.py and home.py in here.

Finally, change your urls.py so there is one more layer in the path.

Here's the old file I was using, with a single views.py:

urlpatterns = patterns('',
    (r'^$', 'bbr.mobile.views.home'),
    (r'^bands/$', 'bbr.mobile.views.bands_az'),
    (r'^bands/([A-Z0-9])/$', 'bbr.mobile.views.bands_letter'),
    (r'^bands/([\w-]*)/$', 'bbr.mobile.views.single_band'),
)

Here's the new one - note that we are now using a longer dot separated path:

urlpatterns = patterns('',
    (r'^$', 'bbr.mobile.views.home.home'),
    (r'^bands/$', 'bbr.mobile.views.bands.bands_az'),
    (r'^bands/([A-Z0-9])/$', 'bbr.mobile.views.bands.bands_letter'),
    (r'^bands/([\w-]*)/$', 'bbr.mobile.views.bands.single_band'),
)

Tags: django views