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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.