【问题标题】:How to access a dictionary value in a for [django, python, html]如何访问 [django, python, html] 中的字典值
【发布时间】:2021-03-16 11:37:28
【问题描述】:

我将context 传递给 html,我需要在 for - 键中显示值。

不显示。如何在循环中引用字典的值?

打印上下文

context = {'tag': 'fast', 'view': <orders.views.OrderAddView object at 0x0000000005AB30A0>, 1: <class 'clients.forms.RelatedAddForm'>, 2: <class 'clients.forms.RelatedAddForm2'>, 'count_form': range(1, 3)}

html

 <form action="{% url 'order_add' tag %}" method="post">
        {% csrf_token %}
        {% for x in count_form %}
            {{ x.as_p }} - this does not work
        {% endfor %}
        {{ 1.as_p }} - it works
        <button type="submit" class="btn btn-primary btn-block">Add order</button>
    </form>

即如何在循环中访问值 1,2 等 - 1: &lt;class 'clients.forms.RelatedAddForm'&gt;

也许有必要在循环中指定{{context [x] .as_p}}?怎么办?

【问题讨论】:

  • 检查 this link 可能有帮助。
  • 为什么不简单地将表单传递到 list 而不是将随机变量名称传递到上下文中?

标签: python django


【解决方案1】:

将所有表单添加到同一个列表中,然后从模板中迭代 forms 键:

context.update({'forms' : [Form1, Form2]})

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2011-07-11
    • 1970-01-01
    • 2012-05-09
    • 2021-09-20
    • 1970-01-01
    • 2021-12-31
    • 2015-08-29
    • 2014-03-18
    相关资源
    最近更新 更多