> Does anybody know how to control a form's output format of a stored > DateField? Unfortunately, different countries use different customs to > represent dates and I'd like to represent the date in another > international format (%d-%m-%Y). Any help would be very much > appreciated!
I use the following combination of formfield and widget: 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']) note that I defined the input formats in my settings as 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' ) subclassing clean() allows me to enter dates without a year specified. If you don't need this you can leave out the clean method definition. and as widget: class DateWidget(forms.DateTimeInput): def __init__(self, attrs={}): super(DateWidget, self).__init__ (format=settings.DATE_OUTPUT_FORMAT) where my setting for the output format is: DATE_OUTPUT_FORMAT = '%d/%m/%Y' (to be honest my real widget also defines some media to use the jquery datepicker) Maybe this helps somebody, cheers, Koen --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---