Django嵌套for循环:是否可以在第二个for循环的定义中使用第一个循环的结果?

2024-09-30 20:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的Django模板中,我试图在for循环中创建一个for循环。我试图使用其中一个字段的结果作为第二个for构造函数中列表的名称。在

有两个对象成功传递到模板:

sectList = {"Id": 1, "Section": "Home", "Identifier": "homeList"}

homeList = {"Id": 1, "Title": "Home", "Url": "home/",
            "Id": 2, "Title": "My Account", "Url": "account/",
            "Id": 3, "Title": "Full List", "Url": "fullList/",}

在我的模板中,我有:

^{pr2}$

在中使用“{%查看”时节标识符%}“,视图.标题返回单词“homeList”,每次迭代拆分一个字符(h、o、m、e等)。当我尝试“{%查看”时{{节标识符}}%}“它给出了以下错误:

TemplateSyntaxError at /

Could not parse the remainder: '{{section.Identifier}}' from '{{section.Identifier}}'

我的问题是如何在for循环的构造函数中使用结果formone queryset?在模板中,节标识符='homeList',视图成功地发送了homeList数据,但它并没有使用视图中的homeList变量,而是将字符串拆分为一个列表,如list(“homeList”),结果是每一行都由单词homeList中的一个字符组成。在常规的python代码中,我可以使用exec之类的代码来执行字符串,但我不确定如何在django模板中执行此操作,如果可能的话?在

编辑1(仅供参考,所有数据均成功传递到模板)

视图.py

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.db import connection, transaction
from app_HomeView.models     import HomeList
from view_LeftPanel.models   import LeftPanelList

def HomeView(request):
    homeList = HomeList.objects.all().order_by("title")
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM view_leftpanelview_sectionlist ORDER BY Id;")
    desc = cursor.description
    sectList = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
    return render(request, "index.html", {"homeList": homeList,
                                          "sectList": sectList,})

Tags: djangofromimport视图模板idurl列表
2条回答

是的您可以,但是您的视图代码传递了错误的值,这就是它不能工作的原因。你有:

sectList = [{"Id": 1, "Section": "Home", "Identifier": "homeList"}]

然后在模板中,在第一个循环之后,section.Identifier的结果显然是"homeList",因此就像您运行:

^{pr2}$

它将打印出“homeList”字符串的每个字符。在

所以您需要做的是将homeList的列表嵌套在secList中,您的{}应该是这样的:

sectList = [{ 
    "Id": 1, "Section": "Home", "Identifier": [  # Identifier should be a list
        {"Id": 1, "Title": "Home", "Url": "home/"},
        {"Id": 2, "Title": "About", "Url": "about/"}
    ] 
}]

这是你的挑战,对吧?在

我想说这个系列应该看起来更像

sectList = {"Id": 1, "Section": "Home",
"Identifier": {"Id": 1, "Title": "Home", 
"Url": "home/","Id": 2, "Title": "My Account",
 "Url": "account/","Id": 3, "Title": "Full List",
 "Url": "fullList/",}}

你会看到-“Identifier”:“homeList”并不是指向第二个列表的链接。只是个道具。名称和值。在

相关问题 更多 >