Hello everyone.
In this article I will show you how to create a custom feed in Django, using the Django Syndication Feed Framework 1.2 or higher.
I’ve had to create an XML with some more tags for each item in the feed.
In particular, in addition to the usual tags present in an RSS feed, I’ve added the
<short_description/>
and
<image/>
tags.
Reading the official documentation of the framework, it is recommended to create a custom feed generator, but the process is not very clear.
Let’s see step by step how to fix everything.
First we create a custom feed generator.
This generator must create the same XML that would produce the framework’s default generator and for each item in the list it will add the new tags.
1 2 3 4 5 | class CustomFeedGenerator(Rss201rev2Feed): |
We see that the generator calls the method add_item_elements(handler, item) of its superclass and then adds new XML tags for each item.
Note that the values that will be inserted in the image and short_description tags must be present in the item dictionary passed as argument.
So let’s create our CustomFeed class that inherits from Feed class and see how to tell it to use the CustomFeedGenerator and how to insert the new values in the item dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class CustomFeed(Feed): |
CustomFeed is very similar to the various feeds that we are accustomed. The only difference is represented by the statement of the type of feed
feed_type = CustomFeedGenerator
and by the method
item_extra_kwargs
able to append any new values in the item dictionary, obtaining the desired result.