Django-rss

提供:Dev Guides
移動先:案内検索

Django-RSS

Djangoには、シンジケーションフィード生成フレームワークが付属しています。 これを使用すると、 _ django.contrib.syndication.views.Feed class_ をサブクラス化するだけでRSSまたはAtomフィードを作成できます。

アプリで行われた最新のコメントのフィードを作成しましょう(Django-Comments Frameworkの章も参照)。 このために、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})
  • フィードクラスでは、 titlelink 、および description 属性は、標準のRSS <title><link> および <description> 要素に対応しています。
  • items メソッドは、項目要素としてフィードに入れる要素を返します。 私たちの場合、最後の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 &plus;= '<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 &plus;= patterns('',
   url(r'^latest/comments/', DreamrealCommentsFeed()),
   url(r'^comment/(?P\w&plus;)/', 'comment', name = 'comment'),
)

/myapp/latest/comments/にアクセスすると、フィードが取得されます-

Django RSSの例

次に、ユーザー名のいずれかをクリックすると、前にコメントビューで定義された/myapp/comment/comment_idが表示されます。

Django RSSリダイレクトページ

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