English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Django è dotato di una struttura di generazione di feed aggregati. Con esso, puoi creare RSS o Atom semplicemente ereditando la classe django.contrib.syndication.views.Feed.
Creiamo un'applicazione per creare una fonte di abbonamento.
# Nome del file: example.py # Copyright: 2020 By w3codebox # Autore: it.oldtoolbag.com # Data: 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 = "Commenti di Dreamreal" link = "/drcomments/" description = "Aggiornamenti sui nuovi commenti nell'articolo 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})
Nella classe feed, gli attributi title, link e description corrispondono agli elementi standard RSS <title>, <link> e <description>.
Il metodo entry restituisce gli elementi degli item che dovrebbero entrare nel feed. Nel nostro esempio sono gli ultimi cinque commenti.
Ora, abbiamo il feed e aggiungiamo i commenti nel file views.py per visualizzare i nostri commenti -
# Nome del file: example.py # Copyright: 2020 By w3codebox # Autore: it.oldtoolbag.com # Data: 2020-08-08 from django.contrib.comments import Comment def comment(request, object_pk): mycomment = Comment.objects.get(object_pk = object_pk) text = '<strong>Utente:</strong> %s <p>'%mycomment.user_name</p> text += '<strong>Commentario:</strong> %s <p>'%mycomment.comment</p> return HttpResponse(text)
Abbiamo bisogno di alcune URL mappate in myapp urls.py -
# Nome del file: example.py # Copyright: 2020 By w3codebox # Autore: it.oldtoolbag.com # Data: 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'), )
Quando si accede a /myapp/latest/comments/ si ottiene feed -
Quando si clicca su uno degli utenti, si ottiene: /myapp/comment/comment_id prima di definire la tua vista dei commenti, si ottiene -
Quindi, definire una fonte RSS come sottoclasse di Feed e assicurarsi che queste URL (una per accedere al feed, una per accedere agli elementi del feed) siano definite. Come commentato, questo può essere collegato a qualsiasi modello del tuo applicativo.