Django-RSS
Djangoには、シンジケーションフィード生成フレームワークが付属しています。サブクラス化するだけでRSSまたはAtomフィードを作成できますdjango.contrib.syndication.views.Feed class。
アプリで行われた最新のコメントのフィードを作成しましょう(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要素として返します。私たちの場合、最後の5つのコメント。
ザ・ 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)
また、マッピングのためにmyappurls.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 /にアクセスすると、フィードが表示されます-

次に、ユーザー名の1つをクリックすると、前にコメントビューで定義された/ myapp / comment / comment_idに移動し、次のようになります。

したがって、RSSフィードの定義は、Feedクラスをサブクラス化し、URL(1つはフィードにアクセスするためのものともう1つはフィード要素にアクセスするためのもの)が定義されていることを確認するだけです。コメントと同じように、これはアプリ内のどのモデルにも添付できます。