Django 简明教程
Django - RSS
Django 带有一个联合提要生成框架。利用此框架,您可以通过对 django.contrib.syndication.views.Feed class 进行子类化来创建 RSS 或 Atom 提要。
让我们创建一个提要,以了解应用程序上进行的最新评论(另请参阅 Django - 注释框架章节)。为此,我们创建一个 myapp/feeds.py 并定义我们的提要(您可以在代码结构中的任何位置放置您的提要类)。
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})
-
在我们的提要类中, title 、 link 和 description 属性对应于标准 RSS <title> 、 <link> 和 <description> 元素。
-
items 方法返回应作为项元素添加到提要中的元素。在我们的示例中,返回的是最近五条评论。
-
item_title 方法将获取作为我们提要项标题的内容。在我们的示例中,标题是用户名。
-
item_description 方法将获取作为我们提要项描述的内容。在我们的示例中,是评论本身。
-
item_link 方法将构建指向完整项的链接。在我们的示例中,会引导您前往评论。
既然我们有了提要,让我们在 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/,您将获得我们的提要 -
然后,单击其中一个用户名将带您访问:/myapp/comment/comment_id (如我们在之前的注释视图中定义的那样),您将获得 -
因此,定义 RSS 提要只是子类化 Feed 类并确保定义 URL(一个用于访问提要,一个用于访问提要元素)的问题。就像注释一样,这可以附加到应用程序中的任何模型。