Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug django (logic) code using django shell in Visual Studio Code

I'm developing a django app including custom logic code using Visual Studio Code and I would like to debug my code while interactie via the django shell. Is this possible and if so, what debugging settings are required?

like image 229
Pim Avatar asked Jul 11 '26 03:07

Pim


2 Answers

You can definitely debug in Django Shell. A typical launch.json configuration for Django Debugging in VSCode already uses manage.py runserver --noreload to launch the dev server, so all you have to do is add an additional debugging config that uses manage.py shell instead, something like this (may require tweaking depending on your project structure):

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

VSCode will launch the Django shell in its build-in terminal.

(Hat-tip to this related discussion about debugging management commands for pointing me in the right direction when I was looking for an answer to this question.)

like image 84
banjo Avatar answered Jul 13 '26 15:07

banjo


Shell is shell and VSCode is VSCode. You cannot debug your code from the shell.

When I need to debug my custom Django code I put debug.py file in my project root (where manage.py is) and load my Django project manually i.e. I imitate the Django shell.

# Here you should use all the logic that you have 
# in manage.py before execute_from_command_line(sys.argv)
# Generally there is only settings module set up:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

# Initialize django application
import django
django.setup()

# Do what you want to debug and set breakpoints
from django.contrib.auth.models import User
User.objects.exists()

Then just run this file using regular Python: Current file debug option

UPD: Now this use-case of Django is docummented: https://docs.djangoproject.com/en/3.0/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage

like image 40
cepbuch Avatar answered Jul 13 '26 17:07

cepbuch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!