[Answer]-Django returns none on web page

0đź‘Ť

âś…

obviously your news() method returns nothing..

The right way should be:

def news():
    YahooContent = feedparser.parse ("http://news.yahoo.com/rss/")
    result = ''
    for feed in YahooContent.entries:
        result += feed.published + '\n'
        result += feed.title + '\n'
        result += feed.link + "\n"
    return result

def html(request):
    html = "<html><body> %s </body></html>" % news()
    return HttpResponse(html)
👤Alfred Huang

1đź‘Ť

You are printing the results, not returning them. In fact, the return statement will return None, just like all methods that don’t have a return statement.

You should build the string in your method itself, like this:

def html(request):
    head = '<html><body>'
    foot = '</body></html>'
    entries = []
    for entry in feedparser.parse("http://news.yahoo.com/rss/").entries:
        entries.append('{}<br />{}<br />{}<br />'.format(entry.published,
                                                   entry.title, entry.link))
    return HttpResponse(head+''.join(entries)+foot)

Can you explain your code a little bit?

Imagine you have a list of “entries”, like this:

entries = [a, b, c]

Each entry has a .published, .title, .link attribute that you want to print as a list in HTML.

You can do this easily by looping through it and using the print statement:

print('<ul>')
for entry in entries:
    print('<li>{0.published} - {0.title} - {0.link}</li>'.format(entry))
print('</ul>')

However, what we need here is to send this data to the browser as a HTML response. We can build the HTML string by replacing print with a string that we keep adding to, like this:

result = '<ul>'
for entry in entries:
    result += '<li>{0.published} - {0.title} - {0.link}</li>'.format(entry)
result += '</ul>'

This will work but is inefficient and slow, it is better to collect the strings in a list, and then join them together. This is what I did in my original answer:

result = ['<ul>']
for entry in entries:
    result.append('<li>{0.published} - {0.title} - {0.link}</li>'.format(entry))
result.append('</li>')

Then I just joined them all up with a header and a footer, and then combined each individual string in the list with a space, and returned it as the response:

 return HttpResponse('<html><body>'+''.join(result)+'</body></html>')
👤Burhan Khalid

Leave a comment