1 | import datetime
|
---|
2 |
|
---|
3 | from django.conf import settings
|
---|
4 | from django.utils import dateformat
|
---|
5 |
|
---|
6 | class 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 |
|
---|
14 | class 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 |
|
---|
26 | class 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
|
---|