djangohacker-news-api

How to Output More than Once In frontend In DJango


I am building a web app that makes use of the HackerNews API and I keep running into the same error.

I am trying to Output the 10 requested result from API but everytime i use the return response it only outputs the first result.

I want it to output 10 articles from the API instead of just the One.

This is my code:

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)

Solution

  • You're only getting one result because your return statement is calling "submission_dict". You probably wanted to call "submission_dict(s)" or something similar but it's hard to tell based on what has been commented out in your code. I think that's your primary problem. Without seeing your template, I don't know what your context object is supposed to look like.

    But try this:

    # 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)
    
    

    And in the template...

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