Blog Archive for February 28, 2010

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()
  DATE_RESOLUTION_CHOICES = (
      ('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 ...

Python Regular Expressions

February 28, 2010

Regular expressions are a powerful way of finding things in strings.

Python

To match a regular expression anywhere in a string, use search:

lRegEx = "\d{4}"
lMatches = re.search(lRegEx, lContestName)
if lMatches:
  raise forms.ValidationError("Contest name cannot contain a year")

To match a regular expression to the beginning ...

Tags: regex python