So, I started learning to code in Python and later Django. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?

我通常只使用Django启用时提供的调试信息。当事情确实像我想象的那样结束时,我用一个语法错误破坏了代码流,并查看流中那个点的变量,以找出代码在哪里做了与我想要的不同的事情。

但这种情况还能改善吗?是否有一些更好的工具或方法来调试Django代码?


当前回答

调试python的最简单的方法——尤其是对习惯于Visual Studio的程序员来说——是使用PTVS (python Tools for Visual Studio)。 步骤很简单:

从https://microsoft.github.io/PTVS/下载并安装它 设置断点并按F5。 您的断点被击中,您可以查看/更改变量,就像调试c# / c++程序一样简单。 这就是全部:)

如果你想使用PTVS调试Django,你需要做以下事情:

在Project settings - General选项卡中,将“Startup File”设置为“manage.py”,这是Django程序的入口点。 在“项目设置-调试”选项卡中,将“脚本参数”设置为“runserver—noreload”。这里的关键点是“—noreload”。如果你不设置它,你的断点就不会被击中。 享受它。

其他回答

从我自己的经验来看,有两种方法:

使用ipdb,这是一个像pdb一样的增强调试器。 导入ipdb;ipdb.set_trace()或breakpoint() (from python3.7) 使用django shell,只需使用下面的命令。这在您开发新视图时非常有用。 Python manage.py shell

我使用pyDev与Eclipse真的很好,设置断点,进入代码,查看任何对象和变量的值,尝试它。

对于那些不小心将pdb添加到实时提交的人,我可以建议这个扩展#Koobz的答案:

@register.filter 
def pdb(element):
    from django.conf import settings
    if settings.DEBUG:    
        import pdb
        pdb.set_trace()
    return element

添加导入pdb;pdb.set_trace()或breakpoint()(形式python3.7)在Python代码中的相应行中执行。执行将在交互式shell中停止。在shell中,您可以执行Python代码(即打印变量)或使用如下命令:

C继续执行 N步到同一函数中的下一行 S步到这个函数或被调用函数的下一行 Q退出调试器/执行

参见:https://poweruser.blog/setting-a-breakpoint-in-python-438e23fe6b28

一个关于模板标签的小窍门:

@register.filter 
def pdb(element):
    import pdb; pdb.set_trace()
    return element

现在,在模板中,您可以执行{{template_var|pdb}}并进入pdb会话(假设您正在运行本地devel服务器),在那里您可以检查元素到您的心的内容。

这是一种很好的方式,可以看到当对象到达模板时发生了什么。