【发布时间】:2019-09-13 01:59:32
【问题描述】:
我正在开发一个 django 应用程序,包括使用 Visual Studio Code 的自定义逻辑代码,我想在通过 django shell 交互时调试我的代码。这可能吗?如果可以,需要哪些调试设置?
【问题讨论】:
标签: visual-studio-code django debugging
我正在开发一个 django 应用程序,包括使用 Visual Studio Code 的自定义逻辑代码,我想在通过 django shell 交互时调试我的代码。这可能吗?如果可以,需要哪些调试设置?
【问题讨论】:
标签: visual-studio-code django debugging
Shell 是外壳,VSCode 是 VSCode。你不能从 shell 调试你的代码。
当我需要调试我的自定义 Django 代码时,我将 debug.py 文件放入我的项目根目录(manage.py 所在的位置)并手动加载我的 Django 项目,即我模仿 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()
然后使用常规的Python: Current file 调试选项运行这个文件
统一更新: 现在记录了 Django 的这个用例: https://docs.djangoproject.com/en/3.0/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
【讨论】:
您绝对可以在 Django Shell 中进行调试。在 VSCode 中用于 Django 调试的典型 launch.json 配置已经使用 manage.py runserver --noreload 来启动开发服务器,因此您所要做的就是添加一个使用 manage.py shell 的额外调试配置,就像这样(可能需要根据具体情况进行调整你的项目结构):
{
"name": "Django Shell",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"shell"
]
}
VSCode 将在其内置终端中启动 Django shell。
(向this related discussion about debugging management commands 致敬,感谢我在寻找这个问题的答案时为我指明了正确的方向。)
【讨论】: