【问题标题】:How can I see all possible attributes of an context variables in django templates如何在 django 模板中查看上下文变量的所有可能属性
【发布时间】:2020-11-04 06:48:18
【问题描述】:

我试图在一个视图中一次使用双模型表单,我正在使用 django-betterforms 来合并它们,它将来自两个模型的所有字段合并到一个表单中。我知道我可以使用不同的 class 和 id 来分隔它们,但我不能以模板形式提取它们,比如

{{ form }}

它将完整的表单放入模板中,我可以像这样渲染所有字段

{% for field in form %}
    {{ field }} or anything
{% endfor %}

我的问题是如何知道该字段的所有可能属性,例如

{{ field.* }} *=anything

类似于dir(field)

这是我面临的一个问题,但是找到所有属性或在两侧分离两个表单的解决方案是什么。基本上我需要分离两个模型,它们会以相同的视图同时保存,但在前端它们会有所不同。

提前致谢!!!

【问题讨论】:

  • dir(field) 有什么问题?你可以把它放在你的python文件中,
  • 但我需要把它放在模板文件中

标签: django django-templates modelform


【解决方案1】:

你创建一个custom filter:

在模板标签/my_filters.py:

from django import template

register = template.Library()

@register.filter
def getallattrs(value):
    return dir(value)

在您的模板中:

{% load my_filters %}
...
{{ field|getallattrs }}

【讨论】:

    猜你喜欢
    • 2013-09-05
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 2023-03-22
    • 2013-07-27
    • 2013-06-07
    • 2010-09-07
    • 2018-06-10
    相关资源
    最近更新 更多