Python – Unable to debug Django processes from vs code

Unable to debug Django processes from vs code… here is a solution to the problem.

Unable to debug Django processes from vs code

I’m trying to debug my Django process from vs code. But I can’t get it to work. In my manage.py:

import ptvsd
try:
    ptvsd.enable_attach("my_secret", address=('localhost', 3000))
except:
    pass

In my docker-compose:

version: '3'

services:
  .db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/ code
    ports:
      - "8000:8000"
      - "3000:3000"
    depends_on:
      -.db

And my debug info in launch.json:

{
  "name": "Attach (Remote Debug)",
  "type": "python",
  "request": "attach",
  "localRoot": "${workspaceFolder}",
  "remoteRoot": "/code",
  "port": 3000,
  "secret": "my_secret",
  "host": "localhost"
},

Dockerfile:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
EXPOSE 3000

When I start a debugging session, I get a message: “The debug adapter process terminated unexpectedly.” Does anyone have any tips on how to make it work? I’m running ptvsd 3.0.0 in my machine and docker container.

Solution

There are three things to check when debugging Django in a Docker environment using VSCode:

  • VSCode remote debugging is currently only available for ptvsd==3.0.0 (see .) VSCode documentation)

  • With docker-compose, ptvsd needs to be appended to the default route 0.0.0.0 in order to be accessible from a host such as a Django development server

  • ptvsd relies on sockets (it can only connect to one port once) and the Django development server reloads manage.py files after every code change in the project. So every time the code is modified, the debugging server connection fails. The best solution to resolve this issue is to attach the ptvsd debugger to the wsgi.py file, which is loaded only once.

Related Problems and Solutions