Amir
Amir

Reputation: 53

Displaying view function in Django

I am trying to display the result of my view function on a Django webpage but only get one line with no hyperlink.

code:

from django.http import HttpResponse
import feedparser

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

Result on the webpage:

Man arrested in death of missing Ariz. girl: http://news.yahoo.com/arizona-girls-home-searched-body-found-154919366.html Thu, 04 Sep 2014 14:05:16 -0400

Upvotes: 0

Views: 60

Answers (2)

alecxe
alecxe

Reputation: 473763

You need to collect feeds in a list and only then, after the loop, return an HttpResponse instance:

content = []
for feed in YahooContent.entries:
    content.append(feed.title + ": " + "\n" + feed.link + "\n" + feed.published)

return HttpResponse('\n'.join(content))

Another option, that would follow Django philosophies about separation of concerns, would be to create and render a template and pass the data into the template context:

  • create a template, let's say index.html with the following content

    <table>
        <tr>
            <th>Title</th>
            <th>Link</th>
            <th>Published</th>
        </tr>
        {% for entry in entries %}
            <tr>
                <td>{{ entry.title }}</td>
                <td>{{ entry.link }}</td>
                <td>{{ entry.published }}</td>
            </tr>
        {% endfor %}
    </table>
    
  • put the template into templates directory of your app or project

  • render it in the view using, for example, render_to_response()

    from django.shortcuts import render_to_response
    import feedparser
    
    def index(content):
        entries = feedparser.parse ("http://news.yahoo.com/rss/").entries
        return render_to_response('index.html', {'entries': entries})
    

Upvotes: 4

Vikas Mishra
Vikas Mishra

Reputation: 65

your 'return' statement is inside the for loop due to which it is returning after the first iteration itself and hence giving just one feed instead of all, to be able to return all feeds you need to build a list of all the feeds and then return that.

Upvotes: 0

Related Questions