Nov

21

Django: First Blood

I realized that markdown will still nicely display code blocks even if there's no fancy syntax colouring (Update: I've got syntax highlighting now. Dig it!), so I thought I'd post the little bit of code I've already written. You may or may not be surprised by just how little I've written to make this thing go. I only have one app, "blog", with one view, and one template. Here's the model:

class BlogPost(models.Model):
"""A simple blog post"""
title = models.CharField(('title'), max_length=100)
slug = models.SlugField(
('slug'), max_length=100, unique_for_date='pub_date')
pub_date = models.DateTimeField(('pub_date'), default=datetime.datetime.now)
body = models.TextField(
('body'), blank=True)
 
class Meta:
verbose_name = ('blog post')
verbose_name_plural =
('blog posts')
ordering = ('-pub_date',)
 
def unicode(self):
return _('%(title)s (Posted: %(pub_date)s)') % {
'title': self.title,
'pub_date': self.pub_date.strftime('%B %d, %Y')
}

I'm trying to stick to Test Driven Development with this project. Here are the tests I've written. The code that makes these tests pass is so boring I won't even post it.

class HomePageTestCase(TestCase):
fixtures = ['test.json']
 
def setUp(self):
self.client = client.Client()
 
def testHomePageLoads(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
 
def testBlogHomeTemplateUsed(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'blog/home.html')
 
def testBlogListInContext(self):
response = self.client.get('/')
self.assertTrue('blogpost_list' in response.context[0])
 
def testBlogPostInResponse(self):
response = self.client.get('/')
self.assertTrue(len(response.context[0]['blogpost_list']) > 0)
blog_post = response.context[0]['blogpost_list'][0]
self.assertContains(response, blog_post.title)