Django附带了一个联合供稿生成框架.有了它,你可以通过继承 django.contrib.syndication.views.Feed class 创建RSS或Atom提要.
让我们创建关于应用程序的最新评论的提要(另请参阅Django - 评论框架章节).为此,让我们创建一个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类中,标题,链接和描述属性对应于标准RSS < ; title> ,< link> 和< description> 元素.
项方法,返回应作为项元素放在Feed中的元素.在我们的案例中,最后五条评论.
item_title 方法将获得我们的Feed项目的标题.在我们的例子中,标题将是用户名.
item_description 方法将获得我们的描述饲料项目.在我们的案例中,评论本身.
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 :
然后单击其中一个用户名将转到:/myapp/comment/在我们的评论视图中定义的comment_id,您将得到 : 去;
因此,定义RSS提要只是对F进行子类化的问题eed类并确保定义URL(一个用于访问feed,一个用于访问feed元素).就像评论一样,这可以附加到您应用中的任何模型.