Markdown + Pygments + Django = Easy

Pygments

I've gotten used to using markdown because of Stack Overflow. One of the coolest features is being able to have your code automatically highlighted. I discovered this is really easy to implement in Django:

Download Libraries

Install the following two libraries:

I did it the easy way by using easy_install:

easy_install pygments
easy_install markdown

Update Models

You need to import the markdown library in your models.py. In my case, I added an additional TextField (body_html) to my Post model to store the rendered HTML. This field will get updated every time the Post is saved. The codehilite extension for the markdown library adds the pygments code highlighting support:

from markdown import markdown

class Post(models.Model):
    title = models.CharField(max_length=128)
    slug = models.SlugField(unique_for_date='publish')
    body = models.TextField()
    body_html = models.TextField(editable=False, blank=True, null=True)

    def save(self):
        self.body_html = markdown(self.body, ['codehilite'])
        super(Post, self).save()

CSS Styling

Take a look at the pygments demo to find a color scheme that you find appealing. I picked the "tango" theme.

The next step is to generate a stylesheet file for your theme:

Since I downloaded the files, I had to do a search/replace for ".highlight" and replace it with ".codehilite" since that is the class that wraps the <pre> code when code blocks are generated.

I then included the stylesheet in my base template for my site:

<link type="text/css" rel="stylesheet" href="{{ MEDIA_URL }}css/pygments/tango.css"/>

I also added some additional styling to the make the code blocks look better in my blog posts (this is SASS code):

.codehilite
    pre
        +round_less
        padding: .5em
        margin: 1em 0
        background-color: #fafafa
        border: solid 1px #ddd
        width: auto
        overflow: auto
        font-family: Consolas, Monaco, Courier New

All Done

It was really that simple. I think I spent more time tweaking the css styling than actually implementing the code.

Categories: Django

Add Comment

Please fill out the form below to add a comment.

Comments are moderated and must be approved before they will appear on the site.

Required — but not publicly displayed. Used to generate a gravatar.

Optional — your name will be hyperlinked to your site.