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?
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With