Dori's Python Life in Words Journal

Creating feeds for blog posts


Django has a built-in syndication feed framework that you can use to dynamically generate RSS or Atom feeds, similar to creating sitemaps using the site framework. A web feed is a data format (usually XML) that makes the most recently updated content available to the user.

# blog/feeds.py

import markdown

from django.contrib.syndication.views import Feed
from django.template.defaultfilters import truncatewords_html
from django.urls import reverse_lazy

from blog.models import Post


class LatestPostsFeed(Feed):
    title = "Dori's Python Life in Words"
    link = reverse_lazy("blog:post_list")
    description = "New posts of my blog."

    def items(self):
        return Post.published.all()[:4]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return truncatewords_html(markdown.markdown(item.body), 30)

    def item_pubdate(self, item):
        return item.publish

Legend:

    • Feed: The Feed class of the syndication feed framework.
    • title, link and description: These are attributes of the Feed class and correspond to the standard RSS elements
    • items(): This method gets the objects to include in the feed, the last 4 published post instances
    • item_title(), item_description() and item_pubdate(): These methods retrieve each object from the items() method and return the title, 30 words of the description body and the publication date.

Now, let's create the a new URL pattern for the feed:

# blog/urls.py

from django.urls import path

from blog.feeds import LatestPostsFeed

app_name = "blog"

urlpatterns = [
    path("latest/feed/", LatestPostsFeed(), name="post_feed"),


Designed by BootstrapMade and modified by DoriDoro