Fix Python – Split in several files


Asked By – barin

My 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

Now we will see solution for issue: Split in several files


In Django everything is a Python module (*.py). You can create a view folder with an inside and you still will be able to import your views, because this also implements a Python module. But an example would be better.

Your original might look like this :

def view1(arg):

def view2(arg):

With the following folder/file structure it will work the same :

views/ :

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

  1., which is what happens in the first (original) case

  2. views/, which is what happens in the second case. Here, is able to provide the view1 method because it imports it.

With this kind of solution, you might have no need to change import or urlpatterns arguments in

If you have many methods in each new view file, you might find it useful to make the imports in views/ use *, 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.

This question is answered By – Vincent Demeester

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0