08 oct 07
In the Django docs, there’s this wonderful little section on coding style. Only recently did I find this myself, as it’s in the section on “Contributing to Django,” which I think most Django users will probably never look at. I think it’s worth pointing out a few things.
1. Follow PEP 8 - although I must admit personally I am not psycho about my line lengths.
2. (PEP 8) Two blank lines between classes and one blank line between my model methods helps with readability.
3. “Use InitialCaps for class names (or for factory functions that return classes).” and “Use underscores, not camelCase, for variable, function and method names.”
4. In templates, do {{ foo }} not {{foo}}. You’d be amazed how much more readable this makes your code.
5. Use the following order on your models: All database fields, class Meta, class Admin, def __unicode__(), def __str__(), def save(), def get_absolute_url(), Any custom methods. It has made me immensely happy that there is an official method to this madness.
1. Can’t find anything official on this, but when importing at the top of a file, I like to do so in the following order: (a) python things, (b) django things, (c) things from my project.
2. Model names should be singular. (Can’t seem to find a link to the official word on this?)
3. Don’t repeat yourself. A friend showed me some code today, and hopefully he’ll forgive me for using him as a guinea pig. Don’t do this:
class Events(models.Model):
eventDate = models.DateTimeField()
eventDoors = models.TimeField(blank=True)
eventName = models.CharField(max_length=200)
eventVenue = models.ForeignKey(Venue)
...
Do this:
class Event(models.Model):
date = models.DateTimeField()
doors = models.TimeField(blank=True)
name = models.CharField(max_length=200)
venue = models.ForeignKey(Venue)
...