Wednesday, July 22, 2009

Djangoism

I don't do as much Django as I'd like any more so going through Form Validation today was a bit of a pain when dealing with a DateTime field. My application places a single entry where data is entered as a ugly DateString 2009-07-22 11:11.

I wanted the form to handle excess whitespace gracefully so:


def clean_when(self):
""" The when field is included by default in the current time zone """
when = self.cleaned_data.get('when')
when = when.strip()
return when


Unfortunately, field validation happens first (at least in this instance), and DateTime was throwing invalid date format errors. Fixing it up I end up with:


class WhiteSpaceDateTimeField(forms.fields.DateTimeField):
""" Work around for is_valid calling clean on the field then the form """
def clean(self, value):
value = value.strip()
value = super(WhiteSpaceDateTimeField, self).clean(value)
return value

No comments:

Post a Comment