Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Custom XML Feed in Django
# -*- coding: utf-8 -*-
Custom Django Feed
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import SyndicationFeed
from django.utils.xmlutils import SimplerXMLGenerator
class CustomSyndicationFeed(SyndicationFeed):
mime_type = 'application/xml'
def write(self, outfile, encoding):
handler = SimplerXMLGenerator(outfile, encoding)
handler.startElement("root", self.root_attributes())
def add_root_elements(self, handler):
# Add root elements here
handler.addQuickElement("my_feed_title", self.feed['title'])
handler.addQuickElement("my_feed_url", self.feed['link'])
def write_items(self, handler):
for item in self.items:
handler.startElement('my_item', self.item_attributes(item))
self.add_item_elements(handler, item)
def _safe_add_element(handler, item, attr):
# Add attribute to xml only if it is present, no empty tags
if item.get(attr):
handler.addQuickElement(attr, item[attr])
def add_item_elements(self, handler, item):
# Handle each element that needs to be added to an xml item
# 'item' is a dict of attributes
handler.addQuickElement('title', item['title'])
handler.addQuickElement('date', item['date'])
handler.addQuickElement('link', item['link'])
handler.addQuickElement('description', item['description'])
self._safe_add_element(handler, item, 'city')
self._safe_add_element(handler, item, 'postalcode')
class CustomFeed(Feed):
feed_type = CustomSyndicationFeed
title = 'Feed title'
link = '/my_models/'
def items(self):
return MyModel.objects.all()
def item_title(self, item):
return item.title
def item_description(self, item):
return item.description
def item_extra_kwargs(self, item):
:type item: MyModel
extra_kwargs = {
# Any additional attributes that you need for an item in your XML
if item.postal_code:
return extra_kwargs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.