ImportError in running django from twisted

I'm trying to run a Twisted program, which serves some requests and also runs a Django app through WSGI, and routes some requests to it. Folder structure is something like this:

code
  |-- __init__.py
  |-- main.py
  |-- django_proj
  |     |-- __init__.py
  |     |-- manage.py
  |     |-- django_proj
  |     |     |-- __init__.py
  |     |     |-- settings.py
  |     |     |-- ...
  |     |-- django_app
  |     |     |-- __init__.py
  |     |     |-- models.py
  |     |     |-- ...

now, in django_proj/django_proj/settings.py I have this line:

INSTALLED_APPS = (
    ...
    'django_proj.django_app',
    ...
)

and I run the program when I'm in code folder like this: python ./main.py, and it runs without problem. But when I need to run something with manage.py, like running manage.py migrate I need to go inside code/django_proj folder and run it; but then it says:

ImportError: No module named django_app

and I need to change the line in INSTALLED_APPS to:

INSTALLED_APPS = (
    ...
    'django_app',
    ...
)

but if I leave it like this, I can't run python ./main.py! Because it will say:

ImportError: No module named django_app

So up until now, I used to change this line back & forth based on what I needed to do at the moment. What should I do to solve this?

Answers


Two solutions: either move manage.py to code (recommended).

Or: use python -m django_proj.manage.

Whatever you choose, you'll have to change all your relative imports to absolute imports. That is, from django_proj.settings to django_proj.django_proj.settings.

Relative imports are nasty and lead the kind of problems you are experiencing now. (This is the reason why relative imports have been removed from Python 3.)

For more information, see this answer from Martijn Pieters.


I see now that your code has an __init__.py. Is it really needed? If not, remove it. If it's needed, then you'll still be using imports relative to code, even with my solution.

This implies that you'll have to move all of your scripts out of code, and prefix all of your imports with code.


Need Your Help

ElasticSearch and Python - Correct methodolgy

python search full-text-search elasticsearch full-text-indexing

I am building a search engine for the list of articles I have. I was advised by a lot of people to use elastic search for full text search. I wrote the following code. It works. But I have a few is...

Append to an array from a string

php arrays post

I've got an array, called $data which needs to be updated with data from an ajax call.