English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Djangoにはフィード生成フレームワークが付属しています。それを使えば、django.contrib.syndication.views.Feedクラスを継承するだけでRSSやAtomフィードを作成できます。
サブスクリプションソースのアプリケーションを作成しましょう。
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ja.oldtoolbag.com # Date : 2020-08-08 from django.contrib.syndication.views import Feed from django.contrib.comments import Comment from django.core.urlresolvers import reverse class DreamrealCommentsFeed(Feed): title = "Dreamrealのコメント" link = "/drcomments/" description = "Dreamrealエントリの新しいコメントの更新" 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クラスでは、title, link, description属性が標準のRSSの<title>, <link>, <description>要素に対応しています。
エントリの最後の五つのコメントがfeedのitemの要素として返されます。
今、feedを持っており、views.pyにコメントを追加して、コメントを表示するためのビューを追加しました。
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ja.oldtoolbag.com # Date : 2020-08-08 from django.contrib.comments import Comment def comment(request, object_pk): mycomment = Comment.objects.get(object_pk = object_pk) テキスト = '<strong>ユーザー :</strong> %s <p>'%mycomment.user_name</p> テキスト +=「コメント :</strong>%s<p>'%mycomment.comment</p> return HttpResponse(text)
myapp urls.pyにURLをマッピングするために必要なURLがいくつかあります。
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ja.oldtoolbag.com # Date : 2020-08-08 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ソースを定義する際には、Feedクラスのサブクラスを定義し、これらのURL(feedにアクセスするためのURLとfeedエレメントにアクセスするためのURL)の定義を確認します。このコメントによると、これらはアプリケーションのいかなるモデルにも接続できます。