English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

RSS Django

Django est doté d'un cadre de génération de flux agrégés. Avec lui, vous pouvez créer un RSS ou un Atom en héritant de la classe django.contrib.syndication.views.Feed.

Let's create a subscription source application.

# Fichier : example.py
# Copyright : 2020 By w3codebox
# Auteur par : fr.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'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})

In the feed class, the title, link, and description properties 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 add comments in the view views.py to display our comments-

# Fichier : example.py
# Copyright : 2020 By w3codebox
# Auteur par : fr.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)

Nous avons besoin de quelques URL pour mapper dans myapp urls.py -

# Fichier : example.py
# Copyright : 2020 By w3codebox
# Auteur par : fr.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'),
 )

Lorsque vous accédez à/myapp/latest/comments/Vous obtiendrez feed -

Lorsque vous cliquez sur l'un des noms d'utilisateur, vous obtiendrez :/myapp/comment/Avant la définition de votre vue de commentaire, comment_id reçoit -

Par conséquent, définir une source RSS en tant que sous-classe de la classe Feed et s'assurer que les définitions de ces URL (une pour accéder au feed, une pour accéder aux éléments du feed) sont définies. Comme mentionné dans les commentaires, cela peut être connecté à n'importe quel modèle de votre application.