目录

Django - RSS

Django附带了一个联合供稿生成框架。 有了它,您可以通过django.contrib.syndication.views.Feed class来创建RSS或Atom提要。

让我们为应用程序上的最新评论创建一个feed(另请参阅Django - Comments Framework章节)。 为此,让我们创建一个myapp/feeds.py并定义我们的feed(您可以将您的feed类放在代码结构中的任何位置)。

from django.contrib.syndication.views import Feed
from django.contrib.comments import Comment
from django.core.urlresolvers import reverse
class DreamrealCommentsFeed(Feed):
   title = "Dreamreal's comments"
   link = "/drcomments/"
   description = "Updates on new comments on Dreamreal entry."
   def items(self):
      return Comment.objects.all().order_by("-submit_date")[:5]
   def item_title(self, item):
      return item.user_name
   def item_description(self, item):
      return item.comment
   def item_link(self, item):
      return reverse('comment', kwargs = {'object_pk':item.pk})
  • 在我们的feed类中, titlelinkdescription属性对应于标准RSS 《title》《link》《description》元素。

  • items方法,返回应作为item元素放在feed中的元素。 在我们的案例中,最后五条评论。

  • item_title方法将获取我们的Feed项的标题。 在我们的例子中,标题将是用户名。

  • item_description方法将获得我们的Feed项目的描述。 在我们的案例中评论本身。

  • item_link方法将构建指向完整项目的链接。 在我们的案例中,它会让你发表评论。

现在我们有了feed,让我们在views.py中添加一个评论视图来显示我们的评论 -

from django.contrib.comments import Comment
def comment(request, object_pk):
   mycomment = Comment.objects.get(object_pk = object_pk)
   text = '<strong>User :</strong> %s <p>'%mycomment.user_name</p>
   text += '<strong>Comment :</strong> %s <p>'%mycomment.comment</p>
   return HttpResponse(text)

我们还需要在myapp urls.py中使用一些URL进行映射 -

from myapp.feeds import DreamrealCommentsFeed
from django.conf.urls import patterns, url
urlpatterns += patterns('',
   url(r'^latest/comments/', DreamrealCommentsFeed()),
   url(r'^comment/(?P\w+)/', 'comment', name = 'comment'),
)

访问/ myapp/latest/comments /时,您将获得我们的Feed -

Django RSS示例

然后单击其中一个用户名将转到:/ myapp/comment/comment_id,如我们的评论视图中所定义,您将获得 -

Django RSS重定向页面

因此,定义RSS提要只是对Feed类进行子类化并确保定义URL(一个用于访问feed和一个用于访问feed元素)。 就像评论一样,这可以附加到您应用中的任何模型。

<上一篇.Django - 注释
Django - AJAX.下一篇>
↑回到顶部↑
WIKI教程 @2018