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代码?


当前回答

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

其他回答

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

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

我使用PyCharm(与eclipse相同的pydev引擎)。真的帮助我能够直观地逐级检查我的代码,并看到发生了什么。

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

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

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

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

我发现Visual Studio Code用于调试Django应用程序非常棒。标准的python启动。Json参数运行python manage.py,并附带调试器,因此你可以设置断点,并按自己的喜好逐步执行代码。

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

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

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