【问题标题】:For loop results line by line printing in template using django view使用 django 视图在模板中逐行打印循环结果
【发布时间】:2021-07-17 08:31:19
【问题描述】:

嗨,我是 django 的新手,我正在尝试使用 django 视图在模板中打印 for 循环结果,但我无法打印所有行

我的看法:

def upload(request):
   cells= [(1,2,3,4),(3,3,4,5)]
   i = 0
   for cell in cells:
      a,b,c.d = cell[0],cell[1],cell[2],cell[3]
      I=[b+d,a+c]
      i=i+1
      print(I)
   return render(request,'res.html',{"text":I})

res.html:

{% for i in text %}
    <div class="row">
        {{ i }}
    </div>
{% endfor %}





when I tried only for loop in python IDE my output is 
    [6, 4]
    [8, 7]
but when I tried in django view I am getting only first row
[6, 4]   and also not able to print this in res.html

请提前帮我解决这个问题

【问题讨论】:

    标签: python django for-loop django-views django-templates


    【解决方案1】:

    您传递给模板的上下文中的“文本”将是我在最后一次循环迭代中的任何内容。也许您想在循环之前声明一个列表,然后在非常迭代时将 I 添加到它。顺便说一句,您应该真正考虑一下您的命名约定,并且仅将大写用于类名而不是用于变量。

    编辑:

    也许它看起来像这样:

    def upload(request):
       cells= [(1,2,3,4),(3,3,4,5)]
       i = 0
       final_results = []
       for cell in cells:
          a,b,c,d = cell[0],cell[1],cell[2],cell[3]
          I=[b+d,a+c]
          i=i+1
          print(I)
          final_results.append(I)
       return render(request,'res.html',{"final_results":final_results})
    

    然后你可以在模板内循环遍历它:

    {% for result in final_results %}
        <div class="row">
            {{ result }}
        </div>
    {% endfor %}
    

    这将在每次循环迭代的 {{result}} 内打印 I。我知道你可能正在尝试,但如果你有一个更具体的例子来说明你想要实现的目标会很好

    【讨论】:

    • @somecallibtules 如果你不介意的话,你能举个例子吗
    • 即使在 cmd 中运行后我也只得到第一行,即 print(I) 我怎样才能得到这个请帮助我@somecallitblues
    【解决方案2】:

    使用这个:

    def upload(request):
        I = []
        i = 0
        cells = [(1, 2, 3, 4), (3, 3, 4, 5)]
        for cell in cells:
            a, b, c, d = cell[0], cell[1], cell[2], cell[3]
            I.append([b+d, a+c])
            print(I)
            i += 1
            return render(request, 'res.html', {"text": I})
    

    【讨论】:

    • 我仍然在我的 html 页面中得到 [6,4] 没有得到两行
    • 在您的 html 页面中打印(len(text))。我在等你的答复。 @编码器
    • 是的,谢谢你上面的答案对我有用 Soroosh 谢谢你的时间
    • 如果您将我的答案标记为答案,我将不胜感激。祝你好运。 @编码器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2010-12-21
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多