【问题标题】:Displaying view function in Django在 Django 中显示视图功能
【发布时间】:2014-10-29 15:17:16
【问题描述】:

我试图在 Django 网页上显示我的视图函数的结果,但只有一行没有超链接。

代码:

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)

网页上的结果:

因失踪的亚利桑那女孩死亡而被捕的男子:http://news.yahoo.com/arizona-girls-home-searched-body-found-154919366.html Thu, 04 Sep 2014 14:05:16 -0400

【问题讨论】:

    标签: python django python-2.7 django-views


    【解决方案1】:

    您需要在列表中收集提要,然后才在循环之后返回一个HttpResponse 实例:

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

    Django philosophies 之后关于关注点分离的另一个选项是create and render a template 并将数据传递到模板上下文中:

    • 创建一个模板,比如index.html,内容如下

      <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>
      
    • 将模板放入你的应用或项目的templates目录

    • 使用例如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})
      

    【讨论】:

    • 可以显示所有内容,但仍将所有内容显示为单个字符串。我希望能够分离新闻并显示超链接。
    • @Amir 好的,我为您提供了另一种更好的方法。
    • 非常感谢,我会试试的。
    【解决方案2】:

    您的“return”语句位于 for 循环中,因为它在第一次迭代之后返回,因此只提供一个提要而不是全部,以便能够返回您需要构建所有提要的列表的所有提要馈送,然后返回。

    【讨论】:

    • 我没有看到 5 分钟后复制答案的意义。此外,如果没有实际的代码,这也无济于事。
    • 我很抱歉,但我之前没有看到你的答案,因为我打开了这个问题,然后去阅读我的邮件,然后输入了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多