Nitay Nitay - 3 years ago 187
Python Question

Can a Python script use a Django database while not being in the same folder?

I have a python application (which we'll call app) I'd like to have a web front for. The application has many files and it's important the folder tree structure stays the way it is.

I've built a Django project and put it in a folder named "Web" in the app's folder, so now the folder tree looks like so:


  • [Data]

  • [Resources]

  • [Web]


    • [WebFront]


      • normal django app files


    • [Web]


      • __init__.py

      • settings.py

      • urls.py

      • wsgi.py


    • __init__.py

    • manage.py


  • main.py



Here's the code on the app's main.py:

import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Web.Web.settings")
django.setup()


This code causes an exception on the
django.setup()
line as (I think) django does not find the project modules:
ImportError: No module named WebFront
(WebFront is the name of the django app)

I suspect this is caused because django runs in the directory of python app, and therefore cannot find the folder
WebFront
- Which should actually be
Web/WebFront


Can this be done? Or should I reverse the order and put the python app in the django app?




This is not a duplicate of the following questions as the folder nesting causes a different problem (I think)


Answer Source

You can locate your main.py script where you like. However, if it is outside of the Web folder, then you will have to add Web to the Python path, otherwise imports like import Webfront are going to fail.

import sys
sys.path.append('/path/to/Web/')

Once you have done that, you can change the DJANGO_SETTINGS_MODULE to

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Web.settings")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download