How to create RSS feed with HTML content in Django

Presenting my solution which I arrived at with trial & error in hopes it could save time to someone.

Published: July 3, 2020
App Store

I am not feeling super comfortable writing this blog post because I don't know much about setting up a RSS feed with Django and including HTML in the content but when I was trying to do this for my own blog I could not find any up-to-date tutorial showing how to properly include HTML content.

I had various issues regarding encoding of the HTML entities so my content was full of stuff like this:

<p>Hello</p>

And when I finally solved this issue I noticed that RSS readers would display the HTML in an "not-rendered" form so readers would see something like this:

<p>Hello <span class="code">World!</span></p>

Instead of properly formatted text based on the HTML provided.

As of right now my RSS feed should be working pretty ok and I hope this little guide will save someone a bit of time when creating their own RSS feed with HTML content and fighting the escaping.

Django has pretty good docs about RSS which will get you started with creating the basic structure, setting up urls etc. But there is very little about providing your custom template and using HTML.

Below is shortened example of my feed:

class BlogPostsFeed(Feed):
    title = "Filip Němeček Blog"
    link = "https://nemecek.be/blog/swift-and-ios"

    description_template = 'rss_feed.html'

The most important part there is the description_template which tells Django where to find template file for individual RSS entries. The alternative is the item_description method but I had zero luck using it with HTML. It works fine if you have plain content and can just pass it along.

And finally let's have a look at my rss_feed.html template file:

{% autoescape off %}
<![CDATA[
{{ obj.title }}

{{ obj.html_content|safe }}
]]
{% endautoescape %}

I am pretty sure this is not the best solution out there but it works fine for me and I have a RSS feed with proper HTML rendering.

RSS feed

The <!CDATA[ wrapper is very important for RSS to display your HTML. But of course it was getting escaped so I turned escaping. The obj is the item automatically passed into the template by Django.

So in my case this is my blog post which has among other stuff a title and html_content attributes.

Please let me know if you have any questions or improvements regarding creating RSS feeds with Django.

Btw there is handy website to test your RSS feed.

Filip Němeček profile photo

WRITTEN BY

Filip Němeček @nemecek_f@iosdev.space

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀