首页 > 解决方案 > 使用 feedparser/RSS,如何在 django 中将 feed 对象从 views.py 传递到 .html?

问题描述

我正在尝试向我的 Web 应用程序添加一个简单的 RSS 解析器。目标是获取一个 RSS 频道并在单个页面上显示来自该频道的新闻。我设法为单个对象执行此操作,但不能为许多对象(例如 10 个)执行此操作。

该项目假设我有文件views.pyRSS.html.

以下 IS 代码适用于单个解析对象。

views.py

import feedparser

def rss(request):
    feeds = feedparser.parse("https://www.informationweek.com/rss_simple.asp")
    entry = feeds.entries[0]
    return render(
        request,
        'posts/rss.html',
        feeds={
            'title': entry.title,
            'published': entry.published,
            'summary': entry.summary,
            'link': entry.link,
            'image':entry.media_content[0]['url']
        }
    )

RSS.html

<h3>{{ title }}</h3>
<i>Date: {{ published }}<p></i>
<b>Summary:</b><p> {{ summary }}<p>
<b>Link:</b><a href="{{ link }}"> {{ link }}</a><p>
<b>Image:</b><p><img src="{{ image }}"></img><p>

我不明白如何将所有提要传递到 RSS.html。

我尝试通过视图传递它,但它不起作用。

以下是不起作用的代码:

views.py

return render(request, 'posts/rss.html', feeds)

RSS.html

{% for entry in feeds %}
    <li><a href="{{entry.link}}">{{entry.title}}</a></li>
{% endfor %}

标签: pythondjangofeedparser

解决方案


将提要对象传递给模板时,您必须遍历entries提要对象的字段:

Python:

import feedparser

def rss(request):
    feed = feedparser.parse("https://www.informationweek.com/rss_simple.asp")
    return render(request, 'posts/rss.html', {'feed': feed})

HTML:

{% for entry in feed.entries %}
    <li><a href="{{entry.link}}">{{entry.title}}</a></li>
{% endfor %}

一般文件:

条目文档:

字典列表。每个字典都包含来自不同条目的数据。条目按照它们在原始提要中出现的顺序列出。


推荐阅读