Gunicorn/Django, ImportError: No module named application.wsgi

Question:

I’m trying to deploy a Django app using Heroku, but I’m running into the following error: “ImportError: No module named myproject.wsgi”.

My project is configured as such:

my-project
│   Procfile
│   requirements.txt
│   runtime.txt
│   README.md
│
├───myproject
│   │   db.sqlite3
│   │   django
│   │   django._file_
│   │   import
│   │   manage.py
|   |
│   ├───myproject
|   |   |    wsgi.py
|   |   |    settings.py
|   |   |    urls.py
|   |   |    _init_.py
|   |   |
|   |   ├───_pycache_
|   | 
│   ├───venv
...

My wgsi.py file is configured as such:

import os
import signal
import sys
import traceback
import time

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

My Procfile contains the following:

web: gunicorn myproject.wsgi:application --log-file -

Why is this producing an error?

Asked By: user6335453

||

Answers:

It seems your running directory is the outermost my-project. Try to change your WSGI application path like gunicorn myproject.myproject.wsgi:application --log-file - and see if the error changes.

I think putting your project in the root directory (i.e. removing the first myproject directory and putting your manage.py in my-project directory) is a requirement for Heroku and will fix your problem.

Answered By: Arman Ordookhani

Extending above answer I tried my WSGI path to gunicorn myproject.myproject.wsgi:application --log-file - and yes error changed now it says ImportError: No module named myproject.settings. To solve this I changed my wsgi file.

FROM:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

TO:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.myproject.settings')

It woked like a charm for me!

Answered By: Muhammad Haseeb

I eventually fixed this using gunicorn’s chdir flag which, as far as I understand it, essentially lets you pretend you’re running gunicorn from another directory. Useful e.g. here where heroku tries to run gunicorn from one directory ‘too low’.

To use it here you’d use in your Procfile:

web: gunicorn --chdir myproject myproject.wsgi:application --log-file -

i.e. you need the new:

--chdir myproject
Answered By: adam

I added gunicorn==20.1.0 to requirements.txt and it fixed the issue.

Answered By: Jon Hebert