views.py has become too big and it's hard to find the right view.
How do I split it in several files and then import it? Does it involve any speed loss?
Can I do the same with
In Django everything is a Python module (*.py). You can create a view folder with an
__init__.py inside and you still will be able to import your views, because this also implements a Python module. But an example would be better.
views.py might look like this :
def view1(arg): pass def view2(arg): pass
With the following folder/file structure it will work the same :
views/ __init__.py viewsa.py viewsb.py
def view1(arg): pass
def view2(arg): pass
from viewsa import view1 from viewsb import view2
The quick explanation would be: when you write
from views import view1 Python will look for view1 in
views.py, which is what happens in the first (original) case
views/__init__.py, which is what happens in the second case. Here,
__init__.py is able to provide the view1 method because it imports it.
With this kind of solution, you might have no need to change
urlpatterns arguments in
If you have many methods in each new view file, you might find it useful to make the imports in
*, like this:
from viewsa import * from viewsb import *
I actually don't know about speed issues (but I doubt there are any).
For Models it might be a bit difficult.
I've had to do this before (for clarities sake)
The way I did this was to create a
views directory, then, in that, create a file called
Now, when you're calling in your
urls.py, you simply need to add another part
For example, previously, you may have called:-
url(r'^calendar/(?P<year>\d\d\d\d)/$', 'myproject.calendar.views.year') url(r'^calendar/(?P<year>\d\d\d\d)/(?P<user>[a-z]+)/$', 'myproject.calendar.views.year_by_user')
You can now call something along the lines of
url(r'^calendar/(?P<year>\d\d\d\d)/$', 'myproject.calendar.views.year.index') url(r'^calendar/(?P<year>\d\d\d\d)/(?P<user>[a-z]+)/$', 'myproject.calendar.views.year.user')
This is, of course, assuming that you had
views/year.py containing the functions