FuzzyDateTimeField is a drop in replacement for the standard DateTimeField that uses dateutil.parser to clean the value. It has an extra keyword argument fuzzy=True
, which allows it to be more liberal with the input formats it accepts. Set fuzzy=False
for more strict validation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from django import forms
import dateutil.parser
class FuzzyDateTimeField(forms.Field):
'''Like a DateTimeField, but uses dateutil.parser to parse datetime.'''
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:
return dateutil.parser.parse(val.strip(), fuzzy=self.fuzzy)
except ValueError, err:
raise forms.ValidationError(*err.args)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.