0

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)

Community
  • 1
  • 1
Nitay
  • 4,193
  • 6
  • 33
  • 42

1 Answers1

2

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")
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • That works! But with 2 issues. One - I still need to point Django to 'Web.Web.Settings` - Shouldn't the path edit fix that? and Two - When I try to import a model I get the error `Model class Web.WebFront.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.` – Nitay Feb 05 '16 at 11:57
  • How are you trying to import the model? What is you `INSTALLED_APPS` setting? – Alasdair Feb 05 '16 at 12:01
  • `from Web.WebFront.models import MyModel`. My `INSTALLED_APPS` just has `WebFront` on the list – Nitay Feb 05 '16 at 12:02
  • 1
    If you have `'Webfront'` in `INSTALLED_APPS`, then you need to add `Web` to the python path using `sys.path.append()`. You should then import the model with `from Webfront.models import MyModel`, and change `DJANGO_SETTINGS_DIR` to `Web.settings`. If that's not working, then I'm not sure what the problem is. Updating your question with the exact code you are trying, the full traceback, and the full path of the folders on your disk might help. – Alasdair Feb 05 '16 at 12:11
  • You're right - The import line was wrong. The correct way is `from WebFront.models import MyModel` – Nitay Feb 05 '16 at 12:13