0

The file "views.py" of my Django application has over 4000 lines of code right now, and it is difficult to scroll down every time to a specific view in my text editor.

I would like to divide this file up into multiple ones.

Is this feasible? I imagine that my "urls.py" would change accordingly. Would I still need to keep my "views.py" file?

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206
  • 1
    Your question has already been answered properly [in this thread](http://stackoverflow.com/questions/2675722/django-breaking-up-views). – pemistahl Jan 19 '12 at 16:43

3 Answers3

8

Unlike models.py, there's nothing magical about the views.py file in Django. A view is simply a function referred to by a URLconf, and that can be in any module at all. Just make sure you refer to it properly, either by giving the full module as text, using the prefix, or importing it:

urls = patterns('',
    (r'url1', 'app.views1.my_view1'),
    (r'url2', 'app.views2.my_view2')
    ...

or

from app import views1, views2
urls = patterns('',
    (r'url1', views1.my_view1),
    (r'url2', views2.my_view2)
    ...

or even:

urls = patterns('app.views1',
    (r'url1', 'my_view1'),
urls += patterns('app.views2',
    (r'url2', 'my_view2'),
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
4

Sure, you can separate your views. You don't have to change your urls either. Just import the other file, and your original views file will inherit everything in the other file.

#views.py
from app.other_view import *

def your_view(request):
    #your code here


#other_view.py
def your_view(request):
    #your code here
jdickson
  • 696
  • 1
  • 9
  • 21
  • 2
    If you're going to use wildcard imports, it's important to combine it with specifying `__all__` in the other view. Otherwise, you end up with namespace pollution. Better yet, don't use wildcard imports and simply explicitly list everything you want to import. – Chris Pratt Jan 19 '12 at 17:00
0

There's ways to break up the default views.py, models.py, etc. files into modules of their own within the app, but I've found this usually ends up creating more problems than it solves.

In general, if you find the files too weighty, it's probably a better use of your time to refactor your code, instead. Do you really need all those views? Is there any way to simplify the logic? Would you benefit from breaking functionality out into an entirely separate app? These are the questions you should ask.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444