如何在 DJango 的前端输出多次

How to Output More than Once In frontend In DJango

我正在构建一个使用 HackerNews API 的网络应用程序,但我一直 运行 陷入同样的​​错误。

我正在尝试从 API 输出 10 个请求的结果,但每次我使用 return 响应时它只输出第一个结果。

我希望它输出 API 中的 10 篇文章,而不仅仅是一篇文章。

这是我的代码:

from operator import itemgetter 
import requests
from django.shortcuts import render

# Make an API call and store the response.
def home(request):
    url = 'https://hacker-news.firebaseio.com/v0/topstories.json' 
    r = requests.get(url)
    print(f"Status code: {r.status_code}")
    # Process information about each submission.
    submission_ids = r.json()
    submission_dicts = []
    for submission_id in submission_ids[:10]:
        # Make a separate API call for each submission.
        url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json" 
        r = requests.get(url)
        print(f"id: {submission_id}\tstatus: {r.status_code}") 
        response_dict = r.json()
        # Build a dictionary for each article.
        submission_dict = {
            'title': response_dict['title'],
            'hn_link': f"http://news.ycombinator.com/item?id={submission_id}", 
            # 'comments': response_dict['descendants'],
        }
        submission_dicts.append(submission_dict)
    # submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), 
    #                             reverse=True)
    for submission_dict in submission_dicts:
        print(f"\nTitle: {submission_dict['title']}")
        print(f"Discussion link: {submission_dict['hn_link']}")
        # print(f"Comments: {submission_dict['comments']}")
    count = 0
    if count < 10:
        return render(request, "news_api/home.html", submission_dict)

您只得到一个结果,因为您的 return 语句正在调用“submission_dict”。您可能想调用“submission_dict(s)”或类似的东西,但很难根据代码中注释掉的内容来判断。我认为这是你的主要问题。没有看到您的模板,我不知道您的上下文对象应该是什么样子。

但是试试这个:

# views.py
def hacker_news_api_selector():
    url = 'https://hacker-news.firebaseio.com/v0/topstories.json' 
    r = requests.get(url)
    submission_list = r.json()
    context = {}
    context['objects'] = []

    # Process information about each submission.
    for submission_id in submission_list[:10]:

        # Make a separate API call for each submission.
        url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json" 
        r = requests.get(url)
        response_dict = r.json()
        context['objects'].append(response_dict)

    return context 

def home(request):
    context = hacker_news_api_selector()
    return render(request, "news_api/home.html", context)

并且在模板中...

# news_api/home.html
<html>
    ...
    {% for x in objects %}
        <li>{{ x.title }}</li>
    {% endfor %}
</html>