模板渲染快捷方式未显示任何结果



我正在尝试将一个变量从我的 views.py 上的pymongo传递给模板。我没有收到任何错误,但我的代码也没有呈现到我的模板。

views.py:

def getTheA(request):
for x in mycol.aggregate([{"$unwind":"$tags"},{'$match': {'tags.tag.name':'A A',}},{'$project': {'url': 1, 'AR': 1, 'tags.tag.name': 1, 'tags.variables': 1, '_id': 0}},]):
theURLs = x['url']
theNames = json.dumps(x['tags']['tag']['name'])
theVars = json.dumps(x['tags']['variables'])
context = {'theURLs' : theURLs}
return render(request, 'templates/a.html', context)

我的HTML代码非常简单。我只是想打印一个网址列表:

<ul>
<li><b>URLSSSS</h1></b>
{% for theURL in theURLs %}
<li>{{ theURL.theURLs }} </li>
{% endfor %}
</ul>

我的结果:

  • 网址

我是Django和MongoDb的新手,似乎无法弄清楚我哪里出错了。

当您在模板中有{{ x.y }}时,这意味着"对象x的属性或字典键y"。

因此,在您的模板中,当您有{{ theURL.theURLs }}时,这意味着"对象theURL的属性或字典键theURLs

theURL已经在循环访问theURLs中的每个对象。 这些对象真的有也命名为theURLs的属性吗? 您的代码中没有任何内容表明情况确实如此。

好吧,在查看了很长时间的代码之后,有两个主要问题。

  1. <li>{{ theURL.theURLs }}</li>应该只是<li>{{ theURL }}</li>
  2. 你的 for 循环严重混乱。 在其当前形式中,您仅采用迭代的最后一个 URL。 以这种方式修复它:

    def getTheA(request): theURLs = [] for yadayadayada: theURLs.append(x['url']) theNames = json.dumps(x['tags']['tag']['name']) theVars = json.dumps(x['tags']['variables']) context = { 'theURLs' : theURLs } return render(request, 'templates/a.html', context=context)

最新更新