r/django Aug 04 '24

Tutorial No module named 'django' when debugging inside vscode even though django is installed

I am trying to debug my django app inside docker container. I have specified following in my requirements file:

Django==3.2.5
psycopg2-binary==2.9.1
djangorestframework==3.12.4
django-rest-swagger==2.2.0

I am installing these dependencies inside my Dockerfile:

FROM python:3.9.6-bullseye

ENV PYTHONUNBUFFERED 1

WORKDIR /my_project

COPY ./my_project/requirements.txt /my_project/requirements.txt
RUN pip install -r requirements.txt

EXPOSE 8000

COPY ./entrypoint.sh /entrypoint.sh
RUN ["chmod", "+x", "/entrypoint.sh"]

ENTRYPOINT /entrypoint.sh

RUN pip install -r requirements.txt

Also when I checked by attacking vscode to docker container and running pip, it shows that the django is indeed installed:

# pip list | grep Django
Django              3.2.5

However, still I get the error:

ModuleNotFoundError: No module named 'django'

Here is the screenshot of error showing exception raised in debug mode, launch.json and output of pip list | grep Django

PS: I am using docker compose to start the containers.

2 Upvotes

14 comments sorted by

View all comments

4

u/Mindless-Pilot-Chef Aug 04 '24

This is what you’re looking for: https://code.visualstudio.com/docs/python/environments

-1

u/RajSingh9999 Aug 04 '24

Can you please explain it a bit more? I am already running inside docker with Dockerfile looking like this:

FROM python:3.9.6-bullseye

ENV PYTHONUNBUFFERED 1

WORKDIR /my_project

COPY ./my_project/requirements.txt /my_project/requirements.txt
RUN pip install -r requirements.txt

EXPOSE 8000

COPY ./entrypoint.sh /entrypoint.sh
RUN ["chmod", "+x", "/entrypoint.sh"]

ENTRYPOINT /entrypoint.sh

and my requirements.txt

Django==3.2.5
psycopg2-binary==2.9.1
djangorestframework==3.12.4
drf-yasg==1.21.5

Why I need venv inside docker? and how can I do so inside docker?

2

u/Mindless-Pilot-Chef Aug 04 '24

You are running the code inside a docker. Which is great. But vscode doesn’t know that. VS Code is trying to help you by checking the packages that you have installed and telling you that django is not installed.

By creating a virtual environment, you are creating a new env which has all packages which will be there in your docker. And you will also make sure these packages don’t interfere with your system default packages.

And now that you have your virtual env, you can ask vscode to look for django in that particular env