Ticket #3672: date-time-formatting-widgets.2.py

File date-time-formatting-widgets.2.py, 1.3 KB (added by scott@…, 18 years ago)

Bug fix: If an invalid date or time is entered the widgets don't try to format it

Line 
1import datetime
2
3from django.conf import settings
4from django.utils import dateformat
5
6class FormattedTextInput(forms.widgets.TextInput):
7 "Overrides TextInput to render formatted value."
8 def render(self, name, value, attrs=None):
9 formatted_value = None
10 if value:
11 formatted_value = self.format_value(value)
12 return super(FormattedTextInput, self).render(name, formatted_value, attrs)
13
14class DateFormattedTextInput(FormattedTextInput):
15 "Renders formatted date."
16 def __init__(self, format=None, attrs=None):
17 super(DateFormattedTextInput, self).__init__(attrs)
18 self.format = format or settings.DATE_FORMAT
19
20 def format_value(self, value):
21 if isinstance(value, datetime.date) or isinstance(value, datetime.datetime):
22 return dateformat.format(value, self.format)
23 else:
24 return value
25
26class TimeFormattedTextInput(FormattedTextInput):
27 "Renders formatted time."
28 def __init__(self, format=None, attrs=None):
29 super(TimeFormattedTextInput, self).__init__(attrs)
30 self.format = format or settings.TIME_FORMAT
31
32 def format_value(self, value):
33 if isinstance(value, datetime.time) or isinstance(value, datetime.datetime):
34 return dateformat.time_format(value, self.format)
35 else:
36 return value
Back to Top