Skip to content

Instantly share code, notes, and snippets.

@MarcDufresne
Last active August 21, 2020 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarcDufresne/bb8792e45a1245614c57 to your computer and use it in GitHub Desktop.
Save MarcDufresne/bb8792e45a1245614c57 to your computer and use it in GitHub Desktop.
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.startDocument()
handler.startElement("root", self.root_attributes())
self.add_root_elements(handler)
self.write_items(handler)
handler.endElement("root")
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)
handler.endElement("my_item")
@staticmethod
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:
extra_kwargs['postalcode']
if item.city:
extra_kwargs['city']
return extra_kwargs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment