Login

FuzzyDateTimeField

Author:
japerk
Posted:
April 9, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

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

  1. codigo alto nivel by MrRocklion 1 month, 1 week ago
  2. Load template from specific app by Krzysiek555 1 month, 4 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 2 months ago
  4. "Magic Link" Management Command by webology 7 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 7 months ago

Comments

Please login first before commenting.