Sometimes we need to nesting applications using sub-folder inside apps of Django. To be able run application in Django using sub-folder, then we can approach this with two ways. For instance, you projects have sub-folder apps like this :
1 2 3 4 5 | PROJECT |_______ sub-folder |____ __init__.py |____ YOUR_APPLICATION_HERE_1 |____ YOUR_APPLICATION_HERE_2 |
Remember, you must create “__init__.py” inside sub-folder which it will threat all python inside as one module packages. To achieve this, we can do in 2 ways. First, by editing your “manage.py” :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #!/usr/bin/env python from django.core.management import execute_manager import imp import os import sys try: imp.find_module(‘settings’) # Assumed to be in the same directory. except ImportError: sys.stderr.write("Error: Can’t find the file ‘settings.py’ in the directory containing %r. It appears you’ve customized things.nYou’ll have to run django-admin.py, passing it your settings module.n" % __file__) sys.exit(1) import settings sys.path.insert(0, os.path.join(os.path.dirname(__file__), "sub-folder")) if __name__ == "__main__": execute_manager(settings) |
You will load apps just like :
1 2 3 | PROJECT |___ YOUR_APPLICATION_HERE_1 |___ YOUR_APPLICATION_HERE_2 |
So there no changes at all. If you don’t want to change manage.py, then you can go to another step, which is mean you should change your configuration like :
1 2 3 4 | INSTALLED_APPS = ( ….., ‘subfolder.apps’, ) |
All imported should use subfolder as primary packages. Because Django use Project as root module path.