Some Notes on a Simple Django Application

Fredrik Lundh | February 2006 | Originally posted to online.effbot.org

Powered by Django.

I just added a simple database-driven “announcement blog” application to the AltPyDotOrgCMS (dead link) demo. This application replaces the manually maintained “announcement” section on python.org, as well as the manually maintained (and not always synchronized) RSS feed.

It took me about an hour to do this, but most of that time was spent on hunting down a weird error message on the deployment machine. First, I created a minimalistic data model (it’s a bit too simple, really, but we can fix that later), and added the admin meta attribute to it:

 
class Announcement(meta.Model):
    text = meta.TextField("Description")
    pubdate = meta.DateTimeField("Publication date")
    enddate = meta.DateTimeField("Publication end date", blank=True)
    class META:
        admin = meta.Admin()

With this in place, I quickly populated the database via Django’s admin interface, and added the necessary views to the templates.

The next step was to tweak the admin interface. As it turned out, adding a nice overview page, with multiple columns, clickable headers, date-based navigation, free-text search for the announcements, and a simple well-formedness check (the check_xml function uses ElementTree to parse the field, and raises an exception if it fails) could be done in about a dozen lines of Python.

 

Here’s the final code, as it looks after a couple of iterations:

class Announcement(meta.Model):

    text = meta.TextField("Description", validator_list=[check_xml])
    pubdate = meta.DateTimeField("Publication date")
    enddate = meta.DateTimeField("Publication end date", blank=True)

    def __repr__(self):
        return "%s - %s" % (self.pubdate, self.get_text_summary())

    def get_text_summary(self):
        from pydotorg.content import tools
        summary = tools.strip_html(self.text)
        if len(summary) > 80:
            summary = summary[:80] + "..."
        return summary
    get_text_summary.short_description = "Summary (plain text)"

    class META:
        ordering = ["-pubdate"]
        admin = meta.Admin(
            list_display=["pubdate", "get_text_summary"],
            date_hierarchy ="pubdate",
            search_fields=["text"]
        )

And here’s a screenshot of the resulting user interface:

 

To add a new entry, click “add announcement”, fill in the text, click “now” to set the publication date, and click “save”. That’s it. Django takes care of the rest.

(related: “…how I wrote a blog in Django, without actually writing any real Python code)

 

A Django site. rendered by a django application. hosted by webfaction.