Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug Django custom management command using VS Code

I am trying to debug a custom management command using Visual Studio Code.

For this I have gone through the official VS Code tutorials for working with Python and Django, and I have managed to get debugging to work while following these tutorials.

VS Code Python tutorial / VS Code Django tutorial

The problem is that for a Python script (no Django), the debugger works because I run a specific file (by pressing f5) while the file's tab is open. Django debugging works because VS Code knows when a browser request causes my Django app to hit a break-point I entered in VS Code.

But a custom management command is run differently. For this I type the following in the console:

python manage.py name_of_management_command

How do I debug this in VS Code?

like image 709
Rik Schoonbeek Avatar asked May 06 '19 16:05

Rik Schoonbeek


2 Answers

While writing this question I came up with a solution myself.

In the VS Code launch.json file (which contains the settings for the VS Code Django debugger) contains the following entry, by default:

"args": ["runserver", "--noreload", "--nothreading"]

I changed this to:

"args": ["name_of_management_command"]

Then start the debugger (press f5), and I am debugging my custom management command

like image 53
Rik Schoonbeek Avatar answered Sep 20 '22 20:09

Rik Schoonbeek


Rik's answer is correct, but requires changing the launch config for every management command, or creating multiple launch config entries.

To create one entry that can debug all management commands, even the ones you still have to write, add the following config to your launch.json:

        {
            "name": "Django MGMT Command",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "${fileBasenameNoExtension}"
            ]
        }

This works because the name of the management command is the name of the file in which it's defined, without the .py extension. Or ${fileBasenameNoExtension} for short.

See https://code.visualstudio.com/docs/editor/variables-reference for other variables you can use in your launch config.

like image 42
jrial Avatar answered Sep 23 '22 20:09

jrial