我正在开发一个django应用程序,包括使用的自定义逻辑代码,并且我希望通过django shell在交互时调试我的代码。这是可能的吗?如果是的话,需要哪些调试设置?
发布于 2019-04-23 20:56:10
外壳是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调试选项运行这个文件
UPD:现在这个Django的用例是文档化的:https://docs.djangoproject.com/en/3.0/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
发布于 2021-04-20 03:11:12
您绝对可以在Django Shell中进行调试。用于Django调试的一个典型的launch.json配置在VSCode中已经使用manage.py runserver --noreload启动了manage.py runserver --noreload服务器,所以您所要做的就是添加一个使用manage.py shell的额外调试配置,类似这样的配置(可能需要根据您的项目结构进行调整):
{
"name": "Django Shell",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"shell"
]
}VSCode将在其内置终端中启动Django外壳。
(感谢this related discussion about debugging management commands在我寻找这个问题的答案时指出了正确的方向。)
https://stackoverflow.com/questions/55818738
复制相似问题