H René,
This is what I use on all my forms (I use my own modelform subclass to
insert these for date fields, but that is not relevant):
as formfield:
class DateFormField(forms.DateField):
def __init__(self, input_formats=None, *args, **kwargs):
super(DateFormField, self).__init__(*args, **kwargs)
self.input_formats = input_formats or
settings.DATE_INPUT_FORMATS
def clean(self, value):
super(forms.DateField, self).clean(value)
if value in forms.fields.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
for format in self.input_formats:
try:
y, m, d = time.strptime(value, format)[:3]
if y == 1900:
y = datetime.datetime.now().year
return datetime.date(y, m, d)
except ValueError:
continue
raise forms.util.ValidationError(self.error_messages
['invalid'])
and as widget:
# like admin date widget with proper date formatting
class DateWidget(forms.DateTimeInput):
class Media:
js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js",
settings.ADMIN_MEDIA_PREFIX + "js/admin/
DateTimeShortcuts.js")
def __init__(self, attrs={}):
super(DateWidget, self).__init__
(format=settings.DATE_OUTPUT_FORMAT, attrs={'class': 'vDateField',
'size': '10'})
and in settings:
DATE_INPUT_FORMATS = (
'%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06'
'%d/%m', # '25/10'
'%Y-%m-%d', # '2006-10-25'
)
DATE_OUTPUT_FORMAT = '%d/%m/%Y'
This way the field accepts all my formats (also the format the
calendar widget returns) and the output is rendered the way I want it.
Notice that the custom clean is there because I want to accept dates
like 18/02 without the year and use the current year for those.
Hope this helps somebody, and would appreciate to hear if there are
better ways,
Koen
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---