簡體   English   中英

試圖了解Django在視圖和模板之間的通信

[英]Trying to understand Django's communication between view and template

(編輯)我來自web2py的背景,發現Django是一個比web2py更復雜的學習和使用框架。

在第一個答案之后,我對問題的描述進行了修改。

我認為我有:

def team(request):
hr = dict(name="Some Name", photo="/static/images/HR.jpg", url="http://some.website.com/?page_id=3602")
js = dict(name="Some Name2", photo="/static/images/JS.jpg", url="http://some.website.com/?page_id=3608")
context = {team:[hr,js]}
return render(request, "wos_2017_2/team.html", context)

在模板中我有

<ul>
   {% for person in context.team %}
   <li> {{ person.name }} {{ person.photo }} {{ person.url }} </li>
   {% endfor %}
</ul>

絕對沒有輸出。

這適用於普通的python:

hr = dict(name="Some Name", photo="/static/images/HR.jpg", url="http://some.website.com/?page_id=3602")
js = dict(name="Some Name2", photo="/static/images/JS.jpg", url="http://some.website.com/?page_id=3608")
context = dict(team = [hr,js])
for i in context['team']:
    print(i['name'], i['photo'], i['url'])

帶輸出

Some Name /static/images/HR.jpg http://some.website.com/?page_id=3602
Some Name2 /static/images/JS.jpg http://some.website.com/?page_id=3608

為什么我在Django中沒有得到任何結果?

您的第一個例子是正確的。 不幸的是,您在第一行代碼中有一個小的錯字:

hr = dict(name="Some Name, ...),

線用逗號結束, 現在hr成為一個具有單個元素的tuple :dict。 沒有逗號,這有效:

{{ team.0.name }}
{{ team.1.name }}

使用更新后的答案,您需要將context.team更改為team中的模板:

{% for person in team %}

上下文字典在模板中“解壓”。

我無法發表評論,所以我不得不發表一個答案。

只能將不可變的數據類型用作鍵,即,不能使用列表或字典。如果將可變數據類型用作鍵,則會收到錯誤消息。

我能說的是問題出在您的視圖代碼中:

這個

context = {team:[hr,js]}

應該是這樣的:

context = {"team":[hr,js]}

要么

context = dict(team=[hr,js])
<ul>
                    {% for person in team %}
                    <li> {{ person.name }} {{ person.photo }} {{ person.url }} </li>
                    {% endfor %}
 </ul>

是讀取模板中詞典的正確方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM