When you start to use VS Code to debug a Django project you may bump into the exception shown in the screenshot above
Exception has occurred: ImportError Couldn't import Django. Are you sure it's installed and available
This post explains how to reproduce the problem and how to resolve it.
The Django project referenced in this post can be found on GitHub and was running in a Python virtualenv. The versions of VS Code and Django used were 1.59 & 3.2.6. respectively.
The problem is caused by the Python interpreter not being set. Jump to the Resolution to see how to select a Python interpreter from within VS Code.
Reproducing the error
If you want to follow along, download the Django project from GitHub. Once done, open the views.py file and add a break point to the return statement, as shown by the red dot on line 6 in the screen shot below.
From VS Code activity bar, select the Run and Debug button, if there isn’t a launch.json file, you will see a link to create one.
Selecting the link opens the Command Palette and displays a list of debug configurations, choose Django.
Accept the default for path to manage.py, the path may need to change but I have found it easier to edit this after launch.json file has been created.
The next step is to amend, if necessary the path where manage.py is located. For the project used in this post, the manage.py file is located within hello_world folder, so the following change to the launch.json file is required.
Save the changes to launch.json and return to Run and Debug. Press the green play button to start debugging the Django project.
After a few moments you will see the error message that shows that Django could not be imported.
Stop the debugger and open the VS Code Command Palette, on Windows this is ctrl + shift + p and start typing:
Python: Select Interpreter
From the resultant list, select the interpreter that matches the virtualenv in use, in this example the virtualenv is called django-helloworld
Press the green play button to start debugging the Django project.
Now you can start the real work of debugging your Django project from VS Code.
Need help debugging your Django project?
Please get in touch.