首页 > 解决方案 > 我如何重定向以循环遍历 django html 中的多个变量

问题描述

我想根据 i 的值转到不同的页面,我知道语法不正确,但我需要一些建议以另一种方式做同样的事情我是堆栈溢出的新手,如果我的问题很愚蠢,请原谅

{% for document,i in details , flag reversed %}
<tr>
    {% if i %}
        <td><li><a href="{{ document.docfile.url}}">{{ document.docfile}}</a></li> </td>
    {%  else %}
        <td><li><a href="./{{ whole }}/{{ document.docfile}}">{{ document.docfile}}</a></li> </td>
    {% endif %}
    <td>{{ document.DateOfUpload}}</td>
    <td>{{ document.emailid}}</td>
</tr>
{% endfor %}

这是视图.py

def getAllFiles(request,project_name,wholepath):
    wholepath=str(wholepath)
    whole=[]
    whole=wholepath.split('/')
    w=len(whole)
    w=w-1
    whole=whole[w]
    wholepath= wholepath.replace('/', '\\')
    wholepath="./media/"+wholepath
    if wholepath:
         getallfiles=Document.objects.filter(parentdirectory=wholepath)
         print(getallfiles)
         flag=[]
         i=0
         for c  in getallfiles:
             i=i+1;
             st=(c.docfile)
             st=str(st)
             print(st,type(st))
             if os.path.isfile(st):
                flag.insert(i,"1")
             else:
                 flag.insert(i,"0")



         return render(request, 'FileView.html', {'details': getallfiles,'whole': whole, 'flag': flag}) 

    else:
        getallfiles=Document.objects.all()
        return render(request, 'AllUploads.html', {'details': getallfiles,'whole':whole}) 

网址.py

  path('projectlist/<slug:project_name>/<path:wholepath>', views.getAllFiles),


如果它是一个文件,那么 url 应该看起来像 ./media/filelocation 或者如果它是一个目录,那么它应该添加以前的路径

标签: djangodjango-templates

解决方案


利用zip_longest

例如,我有 3 个列表:

from itertools import zip_longest

list1=[1,2,3]
 list2=['a','b','c']
 list2=[5,6,7] 

 list=list(zip_longest(list1,list2,list3))
for x,y,z in list:
 print(x,y,z)

输出:

1 a 5
2 b 6
3 c 7

推荐阅读