Created
August 14, 2014 23:05
-
-
Save ryanpitts/efb5399f39a827317172 to your computer and use it in GitHub Desktop.
FuzzyDateFields for Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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