【问题标题】:How to redirect to page multiple times and update information on page with django如何多次重定向到页面并使用 django 更新页面上的信息
【发布时间】:2020-10-08 01:24:10
【问题描述】:

我正在开发一个网络应用程序。 webapp 有一个视图,其中 for 循环运行并在每次迭代时更新三个列表。列表的长度存储在字典中。我想在每次迭代后在模板上显示列表的长度。我该怎么做呢?到目前为止,这是我的代码

views.py

def update_lst(request):
   if request.method == 'POST':
       lst1, lst2, lst3 = [], [], []

       for i in range(10):
           lst1.append(i+1)
           lst2.append(i+2)
           lst3.append(i+3)

           context = {'length1':len(lst1), 'length2':len(lst2), 'length3':len(lst3)}
           render(request, 'details.html', context)

        return redirect('index.html')

    return render(request, 'index.html')

details.html

<h1>Extracting details</h1>
<p>{{length1}}: length of list1</p>
<p>{{length2}}: length of list2</p>
<p>{{length3}}: length of list3</p>

现在 for 循环中的渲染函数没有执行。我做错了什么?

【问题讨论】:

    标签: python django django-views render


    【解决方案1】:

    我认为有两个问题,首先是您在 render 语句前面缺少 return 关键字。其次,您的缩进已关闭。试试这个:

    def update_lst(request):
       if request.method == 'POST':
           lst1, lst2, lst3 = [], [], []
    
           for i in range(10):
               lst1.append(i+1)
               lst2.append(i+2)
               lst3.append(i+3)
    
           context = {'length1':len(lst1), 'length2':len(lst2), 'length3':len(lst3)}
    
           # you code is missing this "return" keyword here
           return render(request, 'details.html', context)
    
        return redirect('index.html')
    

    【讨论】:

    • 渲染函数在for循环之外。每次迭代后如何更新页面?
    【解决方案2】:

    return 中插入context

    return redirect('index.html', context)
    

    您的代码return index.html 没有任何context

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2010-11-08
      • 1970-01-01
      • 2018-03-26
      • 2022-01-22
      相关资源
      最近更新 更多