Skip to content

Using VSCode to Debug Django

Reece Mathews edited this page Feb 13, 2021 · 6 revisions

Setting up the dev environment

VSCode can be used to edit and debug files on remote environments using the Remote-SSH extension by Microsoft. This enables easy line-by-line debugging of the Django project hosted in a virtual machine.

The extension will need to login to the virtual box as root in order to edit files and setup a workspace in /var/django on the box. If the root account does not already have a password, create one by with sudo passwd root in the virtual box.

In VSCode, search for and install the Microsoft Remote-SSH extension from the extensions view (icon on left side-bar).

Click the new Remote "Quick Access" status bar item in the lower left corner of VSCode

Select Remote-SSH: Connect Current Window to Host and enter ssh root@hostname where hostname is the virtual box's internal IPv4 address (192.168...).

Enter the new root password when prompted (there may be multiple prompts)

Go to File>Open Folder and browse to /var/django

Search for and install the Microsoft Python extension to enable Python debugging. Likewise install Microsoft's Pylance extension if better intellisense is desired. Install both of these extensions on the remote host as well using the prompts in the extensions view.

Open the command pallete (View>Commmand Pallete) and search for and run the Python: Select Interpreter command. Enter or select the virtual environment interpreter created by provisions.sh at /usr/bin/venv/bin/python

Open the VSCode run (debug) view from the icon on the left side-bar and click create a launch.json file If Python is in the list of options presented, select it and then Django and enter the path to the debugView.py file: ${workspaceFolder}/ops/ops/debugView.py. If for some reason, Python is not an option, close the prompt with Escape and create or open the .vscode folder in the open director (/var/django/.vscode). Inside .vscode, create or open launch.json and insert the following launch configuration:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/ops/ops/debugView.py",
            "args": [
                "runserver"
            ],
            "django": true
        }
    ]
}

Finally, create or edit a .env file in the open directory and set the PYTHONPATH env var to the root of the Django project: PYTHONPATH=ops/

Now you can edit ops/ops/debugView.py to target whatever view is desired, add breakpoints to the files that will be run, and launch the debugger by clicking the Run icon in the run (debug) view (or from Run>Start Debugging).