Django Tutorial Review
http://www.flickr.com/photos/stevewall/1095860966/
Don't forget to commit
Commit early and often! Every time your code is working with a new
feature or bugfix, you should commit it so that you have that snapshot
available later if you need to come back to it. Use hg
status frequently to make sure you haven't forgotten to add any
files (or add them to your .hgignore). Don't leave files around
showing a ? in hg status: if they should be
added, hg add them; if they should be ignored, put them
in .hgignore.
I'll often use Mercurial to clone a copy of your work that I can play with locally. As far as I'm concerned, if it isn't committed it doesn't exist.
Be hygienic
If you're using Mercurial properly you can delete stuff fearlessly, rather than leaving big ugly chunks of commented code laying around. If you need to go back to what you had before, it's there in your revision history.
BlogPost
class BlogPost(object):
#...
def as_html(self):
" Return HTML-formatted blog post. "
lines = [
'<h3 class="post_title"><a href="#permalink">%s</a></h3>' % self.title,
'<span class="post_author">%s</span>' % self.author,
'<span class="post_date">%s</span>' % self.pub_date
]
for paragraph in self.content.split('\n\n'):
lines.append('<p>%s</p>' % paragraph)
return '\n'.join(lines)
Notes
- In general, use string-formatting (%s) and build up lists of lines to join; avoid string-concatenation with +.
- Use semantic HTML. Your HTML should define only
the meaning of things, not how they are
displayed. For instance, this means the
<br>tag should only be used in places where a linebreak is semantically meaningful; i.e. poetry, or a mailing address. - In reality, we'll almost never generate HTML in Python code like that. Mixing code and HTML makes things hard to maintain; use templates instead.
Classes and methods
Note that methods can be assigned and passed around just like regular functions. Even if you aren't passing arguments, you always use () to call a function or method:
>>> my_post = BlogPost(title='My Title', content='some content') >>> f = my_post.as_html >>> f <bound method BlogPost.as_html of <blog.BlogPost object at 0x7f9414188310>> >>> my_post.as_html <bound method BlogPost.as_html of <blog.BlogPost object at 0x7f9414188310>> >>> f() '<h3 id="post_title">...' >>> my_post.as_html() '<h3 id="post_title">