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


当前回答

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

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

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

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

其他回答

我强烈建议使用PDB。

import pdb
pdb.set_trace()

您可以检查所有变量值,进入函数和更多。 https://docs.python.org/2/library/pdb.html

用于检查对数据库的各种请求、响应和命中。我正在使用django-debug-toolbar https://github.com/django-debug-toolbar/django-debug-toolbar

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

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

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

有很多方法可以做到这一点,但最直接的是简单 使用Python调试器。只需在Django视图函数中添加如下一行:

import pdb; pdb.set_trace()

or

breakpoint()  #from Python3.7

如果您试图在浏览器中加载该页,浏览器将挂起,并提示您对实际执行的代码进行调试。

但是也有其他的选择(我不推荐):

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

但是对于所有类型的Python代码,强烈推荐使用Python调试器(pdb)。如果您已经开始使用pdb,那么您还需要了解使用ipython进行调试的IPDB。

对pdb有一些更有用的扩展

pdb++,由Antash建议。

pudb,由PatDuJour建议。

在Django中使用Python调试器,由Seafangs建议。

大多数选项都已经提到了。 为了打印模板上下文,我为此创建了一个简单的库。 参见https://github.com/edoburu/django-debugtools

你可以使用它来打印模板上下文,而不需要任何{% load %}结构:

{% print var %}   prints variable
{% print %}       prints all

它使用定制的pprint格式在<pre>标记中显示变量。