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


当前回答

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

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

其他回答

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

我已经把django-pdb推到了PyPI。 这是一个简单的应用程序,这意味着你不需要编辑你的源代码,每次你想进入pdb。

安装只是…

PIP安装django-pdb 添加'django_pdb'到你的INSTALLED_APPS

你现在可以运行:manage.py runserver——pdb在每个视图的开始进入pdb…

bash: manage.py runserver --pdb
Validating models...

0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}

> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)

然后运行:manage.py test——pdb在测试失败/错误时进入pdb…

bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
    one_plus_one = four
NameError: global name 'four' is not defined
======================================================================

> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)

该项目托管在GitHub上,当然欢迎贡献。

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

到目前为止,几乎所有的东西都已经提到了,所以我只补充一点,可以使用ipdb.set_trace()而不是pdb.set_trace(),它使用iPython,因此更强大(自动完成和其他好东西)。这需要ipdb包,所以你只需要pip安装ipdb

有一些工具配合得很好,可以使您的调试任务更容易。

最重要的是Django调试工具栏。

然后需要使用Python日志工具进行良好的日志记录。您可以将日志输出发送到日志文件,但更简单的选择是将日志输出发送到firepython。要使用此功能,您需要使用带有firebug扩展的Firefox浏览器。Firepython包含一个firebug插件,可以在firebug选项卡中显示任何服务器端日志记录。

Firebug本身对于调试您所开发的任何应用程序的Javascript方面也很重要。(当然前提是你有一些JS代码)。

我也喜欢django-viewtools,它可以用pdb交互地调试视图,但是我不怎么用它。

还有更有用的工具,如dozer,可以跟踪内存泄漏(在SO的回答中也有其他关于内存跟踪的好建议)。