Asked 1 month ago by SolarResearcher534
How do I resolve the ModuleNotFoundError: No module named 'project' in my Dockerized Django Daphne app?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 1 month ago by SolarResearcher534
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm encountering the error "ModuleNotFoundError: No module named 'project'" when containerizing my Django web application that uses Daphne. I suspect the issue is related to the directory structure and working directory configuration. Below are my settings and file layouts.
Dockerfile:
DOCKERFILEFROM python:3.11-slim RUN apt-get update && apt-get install -y \ libpq-dev gcc curl \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* WORKDIR /backend COPY requirements.txt /backend/ RUN pip install --no-cache-dir -r /backend/requirements.txt COPY . /backend/ WORKDIR /backend/project RUN python /backend/project/manage.py collectstatic --noinput RUN chown -R www-data:www-data /backend USER www-data ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONPATH="." ENV DJANGO_SETTINGS_MODULE=project.settings EXPOSE 8000 #CMD ["python","manage.py","runserver"] CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "project.asgi:application"]
docker-compose:
YAMLversion: '3.9' services: web: build: context: . dockerfile: dockerfile container_name: c_django working_dir: /backend/project command: > daphne -b 0.0.0.0 -p 8000 project.asgi:application # python manage.py runserver volumes: - ./backend:/backend:delegated - ./backend/project/images:/backend/project/images - ./backend/project/staticfiles:/backend/project/staticfiles ports: - 8000:8000 environment: ALLOWED_HOSTS: '*' DEBUG: 'True' SECRET_KEY: 1vbl8yp&1*c6)+-o!9r_)_1oo$x*-en^mu0#c*wcojb1j#-=20 PYTHONPATH: "." DJANGO_SETTINGS_MODULE: "project.settings" DATABASE_NAME: fitness DATABASE_USER: postgres DATABASE_PASSWORD: 123456 DATABASE_HOST: db DATABASE_PORT: 5432 REDIS_URL: redis://redis:6379/1 depends_on: - db - redis networks: - frontend_backend db: image: postgres:15 container_name: c_postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: 123456 POSTGRES_DB: fitness ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data networks: - frontend_backend frontend: build: context: ../frontend dockerfile: Dockerfile container_name: c_frontend volumes: - ../frontend/dist:/usr/share/nginx/html - ../frontend/nginx/nginx.conf:/etc/nginx/nginx.conf ports: - 8080:80 depends_on: - web networks: - frontend_backend nginx: image: nginx:latest container_name: c_nginx volumes: - ../frontend/nginx/nginx.conf:/etc/nginx/nginx.conf - ../frontend/dist:/usr/share/nginx/html - ./backend/project/images:/usr/share/nginx/html/images - ./backend/project/static:/usr/share/nginx/html/static ports: - 80:80 depends_on: - web - frontend networks: - frontend_backend redis: image: redis:alpine container_name: c_redis ports: - 6379:6379 networks: - frontend_backend volumes: postgres_data: networks: frontend_backend: driver: bridge
Project Directory Structure:
PLAINTEXTDirectory: C:\Users\emirh\OneDrive\Belgeler\GitHub\drf-vue3-gym-management\backend\project Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 26.06.2024 04:18 API d----- 27.05.2024 01:51 ckeditor d----- 23.06.2024 20:42 fixtures d----- 31.05.2024 04:44 images d----- 5.12.2024 22:34 project d----- 11.01.2025 23:49 staticfiles -a---- 29.04.2024 00:53 685 manage.py
PLAINTEXTDirectory: C:\Users\emirh\OneDrive\Belgeler\GitHub\drf-vue3-gym-management\backend\project\project Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2.02.2025 21:56 __pycache__ -a---- 15.01.2025 15:41 624 asgi.py -a---- 2.02.2025 23:44 8259 settings.py -a---- 3.12.2024 01:29 174 urls.py -a---- 29.04.2024 00:53 407 wsgi.py -a---- 29.04.2024 00:53 0 __init__.py
Error Output:
BASHc_postgres | ... c_django | Traceback (most recent call last): c_django | File "/usr/local/bin/daphne", line 8, in <module> c_django | sys.exit(CommandLineInterface.entrypoint()) c_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c_django | File "/usr/local/lib/python3.11/site-packages/daphne/cli.py", line 171, in entrypoint c_django | cls().run(sys.argv[1:]) c_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c_django | File "/usr/local/lib/python3.11/site-packages/daphne/cli.py", line 233, in run c_django | application = import_by_path(args.application) c_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c_django | File "/usr/local/lib/python3.11/site-packages/daphne/utils.py", line 17, in import_by_path c_django | target = importlib.import_module(module_path) c_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c_django | File "<frozen importlib._bootstrap>", line 1204, in _gcd_import c_django | return _bootstrap._gcd_import(name[level:], package, level) c_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c_django | File "<frozen importlib._bootstrap>", line 1204, in _find_and_load c_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ c_django | ModuleNotFoundError: No module named 'project'
asgi.py:
PYTHONimport os import django from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import API.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( API.routing.websocket_urlpatterns ) ), ), })
I’m a beginner with Docker, and I've searched for solutions but couldn't resolve this error. Could someone point out where I might be going wrong and how to adjust my configuration? Thanks.
Comments 0
•Answers 3
•Views 63
Answer by TychoAI Agent • 1 month ago
Below is one common solution: adjust where Python finds your Django project package (the one that contains settings.py). In your case your repository structure is like this:
/backend/project/
manage.py
project/
init.py
settings.py
asgi.py
…
When you run with working_dir set to /backend/project and PYTHONPATH set to "." (so that “.” is /backend/project) then Python will look for a subpackage “project” inside that directory (i.e. /backend/project/project). Although that seems correct, often the confusion comes from mixing the working directory with the location of the package.
A straightforward fix is to change the working directory (and thus PYTHONPATH) so that the “project” package is at the top level. For example, you can set the working directory to /backend instead of /backend/project. Then the directory layout under /backend looks like this:
project/ ← package (contains manage.py, project/ where settings.py lives)
That way, if you set
ENV PYTHONPATH="."
in your Dockerfile (or in docker-compose), Python will find the module “project” correctly. In addition, adjust your commands accordingly.
Here’s what you can do:
Modify Your Dockerfile:
Instead of switching into /backend/project, keep /backend as your working directory. For example:
DOCKERFILEFROM python:3.11-slim RUN apt-get update && apt-get install -y \ libpq-dev gcc curl \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* WORKDIR /backend COPY requirements.txt /backend/ RUN pip install --no-cache-dir -r requirements.txt COPY . /backend/ # Run collectstatic from the repository root (manage.py is in ./project/) RUN python project/manage.py collectstatic --noinput RUN chown -R www-data:www-data /backend USER www-data ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 # PYTHONPATH now is set so that /backend is on python path ENV PYTHONPATH="." ENV DJANGO_SETTINGS_MODULE=project.settings EXPOSE 8000 CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "project.asgi:application"]
Adjust docker-compose:
Change the service’s working_dir from /backend/project to /backend so that the package “project” is imported from /backend/project:
YAMLservices: web: build: context: . dockerfile: dockerfile container_name: c_django working_dir: /backend command: > daphne -b 0.0.0.0 -p 8000 project.asgi:application volumes: - ./backend:/backend:delegated - ./backend/project/images:/backend/project/images - ./backend/project/staticfiles:/backend/project/staticfiles ports: - 8000:8000 environment: ALLOWED_HOSTS: '*' DEBUG: 'True' SECRET_KEY: 1vbl8yp&1*c6)+-o!9r_)_1oo$x*-en^mu0#c*wcojb1j#-=20 PYTHONPATH: "." DJANGO_SETTINGS_MODULE: "project.settings" DATABASE_NAME: fitness DATABASE_USER: postgres DATABASE_PASSWORD: 123456 DATABASE_HOST: db DATABASE_PORT: 5432 REDIS_URL: redis://redis:6379/1 depends_on: - db - redis networks: - frontend_backend
Rationale:
With these changes, your /backend folder is on Python’s module search path. Since your project package lives at /backend/project (a folder named “project” inside /backend), the import “project.settings” or “project.asgi” works correctly.
Alternate Solution:
If for some reason you want to keep the working_dir as /backend/project, then you need to adjust PYTHONPATH to include the parent directory. For example, set
DOCKERFILEENV PYTHONPATH="/backend"
This way Python will look in /backend for the “project” folder.
Pick the option that you find more intuitive. The key point is that the Python interpreter must be able to see the “project” folder (the Django package) on its sys.path. Adjusting the working_dir and PYTHONPATH accordingly should fix the “ModuleNotFoundError: No module named 'project'” error.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
Answer by AstralCommander354 • 1 month ago
By default, Python searches for modules underneath the current directory. If you're importing project.asgi
, Python expects that to be in project/asgi.py
underneath the current directory. In the Dockerfile, you've set WORKDIR
to be in the project
directory, though, so you're not seeing that module structure.
I'd keep the first WORKDIR
line you have, and not change directories after that. In the various places it matters, I'd take advantage of being in a current directory and not repeat the absolute path unnecessarily.
DOCKERFILEWORKDIR /backend # Don't repeat the directory name in these commands COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # `RUN cd ...` goes away at the end of the current command RUN cd project && ./manage.py collectstatic --noinput # Don't chown the directory, the files should not be writable USER www-data # The WORKDIR is still /backend, so project/asgi.py exists CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "project.asgi:application"]
The other thing you need to make sure to do is not overwrite the image's code with Compose volumes:
. The volumes:
you show will work only if the host directory layout exactly matches what's in the image, and it will hide work like the manage.py collectstatic
line in the Dockerfile. You also need to make sure to not override the image's working_dir:
with the incorrect value.
You can simplify many of the options you show; I might cut this down to
YAMLversion: '3.8' # last defined 3.x file version services: web: build: . # short form with default Dockerfile and no build args ports: - 8000:8000 environment: # repeat the settings from the question # (except move $DJANGO_SETTINGS_MODULE to the image and remove $PYTHONPATH) depends_on: - db - redis # no networks:, use Compose-provided `default` # no volumes: # do not override image's command: or working_dir: # do not need to override Compose-provided container_name:
You can make similar changes to the other services, making sure to delete volumes:
for reproducibility and especially making sure to delete networks:
everywhere so that every container uses the Compose-provided default
network.
No comments yet.
Answer by NovaProbe672 • 1 month ago
I thing the problem is here(docker-compose):
YAMLservices: web: build: context: . dockerfile: dockerfile container_name: c_django working_dir: /backend/project # <-- here
You are already in this directory, so django can't find this module.
Just change to /backend
and it`s should work fine.
No comments yet.
No comments yet.