Skip to content

Instantly share code, notes, and snippets.

@ryanpitts
Created August 14, 2014 23:05
Show Gist options
  • Save ryanpitts/efb5399f39a827317172 to your computer and use it in GitHub Desktop.
Save ryanpitts/efb5399f39a827317172 to your computer and use it in GitHub Desktop.
FuzzyDateFields for Django
import datetime
import dateutil.parser
from django import forms
class FuzzyDateTimeField(forms.Field):
'''
Like a DateTimeField, but uses dateutil.parser to parse datetime.
http://www.djangosnippets.org/snippets/1422/
'''
def __init__(self, widget=forms.DateTimeInput, fuzzy=True, **kwargs):
forms.Field.__init__(self, widget=widget, **kwargs)
self.fuzzy = fuzzy
def clean(self, val):
super(FuzzyDateTimeField, self).clean(val)
if not val:
return None
elif isinstance(val, datetime.datetime):
return val
try:
dt = dateutil.parser.parse(val.strip(), fuzzy=self.fuzzy)
if dt.year > 1900:
return dt
else:
raise forms.ValidationError('please enter a valid date')
except ValueError, err:
raise forms.ValidationError(*err.args)
class FuzzyDateField(forms.Field):
'''
Like a DateField, but uses dateutil.parser to parse date.
http://www.djangosnippets.org/snippets/1422/
'''
def __init__(self, widget=forms.DateInput, fuzzy=True, **kwargs):
forms.Field.__init__(self, widget=widget, **kwargs)
self.fuzzy = fuzzy
def clean(self, val):
super(FuzzyDateField, self).clean(val)
if not val:
return None
elif isinstance(val, datetime.date):
return val
try:
d = dateutil.parser.parse(val.strip(), fuzzy=self.fuzzy)
if d.year > 1900:
return d
else:
raise forms.ValidationError('please enter a valid date')
except ValueError, err:
raise forms.ValidationError(*err.args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment