Jay Parlar



Internal post structure change


Tags: django

Inspired by James' post on blank and null in Django, I decided to change my own internal Post object.

Before, I was rendering my posts with Markdown whenever someone would view it. But as James said, on a shared host, disk space is much cheaper than CPU.

So what I did instead was override the save() method of my Post model. It now looks like this:

def save(self):
    self.body_html = markdown(self.body)
    super(Post, self).save()

What's this doing? Well, whenever a save is done, I convert the field I entered the text in (self.body) into HTML via the builtin Markdown converter.

Notice that my field definition for this new field is:

body_html = models.TextField(blank=True)

It's allowed to be blank, because in the Admin, I won't be entering directly into it. However, it's not allowed to be null, because something has to get saved there, hence the save() method.

I also changed my templates to remove the Markdown filtering, and to use the new field.

Comments still use Markdown though on render, not sure about the best way to fix that (as I'm using Django's built in comments framework, so I can't just override the method. Not cleanly, at least).

Probably the trickiest thing for me, in doing this, was upgrading the database to have the new field. It wasn't hard, mind you, but I'm a relative newbie when it comes to SQL. This is what I did:

alter table blog_posts add column `body_html` longtext NOT NULL;

Was there a better way to do that?

I didn't just want to blow away my table and do a python manage.py syncdb, because then I'd lose all my current posts. I'm certainly going to have to get better with SQL though, if I'm going to keep updating my code and models like this.

Also, because I only had a few posts, I just went into each one in the Admin and pressed the Save button. That automatically called the new save() method. However, if I had had a lot more posts, I would have whipped together a quick script to do it for me. Something like:

from jayparlar.blog.models import Post
for post in Post.objects.all():
    post.save()

Comments

Post a comment



What should go into the right column, when I already have links in the left column?

www.flickr.com
This is a Flickr badge showing public photos from Jaybp. Make your own badge here.

Subscribe to Jay's blog

Get Firefox
Dreamhost Button
Powered by Django.