簡體   English   中英

for循環中的迭代問題(Python3 + Django)

[英]iterating issue in a for loop (Python3 + Django)

我是新手,所以請善待,在我的 django 項目中開發一個博客應用程序,這個想法是檢查是否有文章,是否有每篇文章的列表。 如果沒有文章,則顯示未找到文章

下面是我的觀點 function,但是當我測試它時,它只列出我列表中的第一個項目,其中 mike,其他名稱沒有顯示在頁面或源上,就像它們不存在一樣??? 對此的任何幫助都會很棒。 提前致謝

def add(request):
    articles=["mike","sammy","ahmed"]
    if not articles :
        return HttpResponse("<body><h1>No Articles to display here</h1></body>")
    else:
        for article in articles:
            return HttpResponse(f"{article}")

在與@TimRoberts 討論后,我做了一些更改

def add(request):
    articles=["mike","sammy","ahmed"]
    count = len(articles)
    if count > 0:
        for article in articles :
            return HttpResponse(f"<li>{article}</li>")
    else:
        return HttpResponse("No articles found here. ")

但這只是返回文章列表中的第一項。 為什么它不在響應中做一個 for each 並迭代列出所有內容?

迭代未列出列表中 python 計數顯示為 3 的所有項目,其唯一列出的麥克

此視圖將始終返回列表的第一個元素,因為您在第一次迭代中返回第一個元素。

視圖通常不返回 HttpResponse 實例,但更頻繁地使用render方法。

這可能是您想要對視圖執行的操作以及它的外觀。

def add(request):
  articles = ["mike", "sammy", "ahmed"]
  context = {
    "articles": articles
  }
  return render(request, "<APP_NAME>/<TEMPLATE_NAME>.html", context)

然后你可以在你的 HTML 模板中處理它。 這樣你的視圖就干凈多了。

如果您不想在模板中編寫邏輯,則可以執行以下操作:

def add(request):
    articles = ["mike", "sammy", "ahmed"]

    context = {
      "articles": articles if articles else ["No Articles to display here"]
    }
    return render(request, "<APP_NAME>/<TEMPLATE_NAME>.html", context)

這樣您就不必在 HTML 模板中編寫任何邏輯(迭代除外)。

您的模板應如下所示:

<body>
  {% for article in articles %}
    {{ article }}
    <br>
  {% endfor %}
</body>

這將在自己的行中顯示每篇文章。

暫無
暫無

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

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