Django Model Choice Fields

February 28, 2010

You can convert any Django CharField into a droplist by specifying options in the model structure. For example:

class ContestEvent(models.Model):
  date_of_event = models.DateField()
      ('D', 'Exact Day'),
      ('M', 'Month'),
      ('Y', 'Year'),
  date_resolution = models.CharField(max_length=1, default='D', choices=DATE_RESOLUTION_CHOICES)

If you don't set a default value, you'll get a blank option in the droplist.

At runtime, you can get the normal value using


You can also get the display version (in this case "Exact Day", "Month" or "Year") using: