Rom*_*man 5 python django django-templates
如何插入pdb.set_trace()django 模板?或者也许在模板内运行一些其他调试。
这是我创建的一个小模板标签,它允许您检查模板中任何给定点的上下文:
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def set_breakpoint(context, *args):
"""
Set breakpoints in the template for easy examination of the context,
or any variables of your choice.
Usage:
{% load breakpoint %}
{% set_breakpoint %}
- or -
{% set_breakpoint your_variable your_other_variable %}
- The context is always accessible in the pdb console as a dict 'context'.
- Additional variables can be accessed as vars[i] in the pdb console.
- e.g. in the example above, your_variable will called vars[0] in the
console, your_other_variable is vars[1]
"""
vars = [arg for arg in locals()['args']] # noqa F841
breakpoint()
Run Code Online (Sandbox Code Playgroud)
将此代码保存在[your_project]/[your_app]/templatetags/your_template_tag.py. (该templatetags文件夹应与 的templates文件夹位于同一目录中[your_app]。)
现在,重新启动服务器。(不要忘记这部分!除非您重新启动服务器,模板标签才会加载!)
现在,您可以通过将以下代码放置在您希望调试器运行的模板中来调用模板标记:
{% load your_template_tag %}
{% set_breakpoint %}
- or -
{% set_breakpoint your_variable %}
Run Code Online (Sandbox Code Playgroud)
瞧!Django 的服务器现在将为您显示一个 pdb shell,您可以在其中检查模板的整个上下文,例如context['request'].path. (您可以通过调用内置函数来查看哪些变量可用locals()。)
显然,这仅供开发使用。不要在生产中运行它,也不要在代码中留下断点。
小智 1
PyCharm专业版支持Django模板的图形化调试。有关如何执行此操作的更多信息如下:
https://www.jetbrains.com/help/pycharm/2016.1/debugging-django-templates.html
PyCharm 的调试器非常非常好。它几乎是目前最好的 Python IDE。
免责声明:我是一个满意的客户,但没有其他既得利益。
| 归档时间: |
|
| 查看次数: |
2987 次 |
| 最近记录: |