English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Django comes with an aggregation feed generation framework. With it, you can create RSS or Atom feeds simply by inheriting from the django.contrib.syndication.views.Feed class.
让我们创建一个订阅源的应用程序。
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 Let's create a subscription source application. from django.contrib.comments import Comment from django.contrib.syndication.views import Feed 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("5submit_date)[: ] 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})
In the feed class, the title, link, and description attributes correspond to the standard RSS's <title>, <link>, and <description> elements.
The entry method returns the elements that should enter the feed item. In our example, it is the last five comments.
Now, we have feed, and we add comments in the view views.py to display our comments-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.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) text = '<strong>User : </strong> %s <p>' % mycomment.user_name</p> text +Comment <strong> : </strong>%s<p>'%mycomment.comment</p> return HttpResponse(text)
We also need some URLs to be mapped in myapp/urls.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.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'), )
When visiting/myapp/latest/comments/You will get feed -
When clicking on any of the usernames, you will get:/myapp/comment/The comment_id will be received before defining your comment view -
Therefore, define an RSS source as a subclass of the Feed class and ensure that these URLs (one for accessing the feed and one for accessing the feed elements) are defined. As mentioned in the comments, this can be connected to any model in your application.