I'm creating a filter
which contains datetime
range choice. I would like user to be able to input date in this format: 24.08.2017 17:09
From docs, it is possible to specify a widget (from django.forms
) and widget has attribute input_formats
.
So this would be a solution:
datetime_range = django_filters.DateTimeFromToRangeFilter(method='datetime',
label=u'Čas od do',widget=forms.widgets.DateTimeInput(format="%D.%m.%Y %H:%M:%S")
The problem is that it uses DateTimeFromToRangeFilter
which uses two DateTimeInput
fields. So if I specify the widget, it renders one DateTimeInput
instead of two inputs.
So the question is, how to specify the format (without changing widget)?
I'm trying to specify input_formats
inside __init__(...)
but it raises:
Exception Value: can't set attribute
def __init__(self,*args,**kwargs):
self.base_filters['datetime_range'].field = (forms.DateTimeField(input_formats=["%D.%m.%Y %H:%M"]),forms.DateTimeField(input_formats=["%D.%m.%Y %H:%M"]))
An easy solution would be to simply modify the DATETIME_INPUT_FORMATS
setting.
Alternatively, you could create a custom field, based on the existing DateTimeRangeField.
class CustomDateTimeRangeField(django_filters.RangeField):
def __init__(self, *args, **kwargs):
fields = (
forms.DateTimeField(input_formats=["%D.%m.%Y %H:%M"]),
forms.DateTimeField(input_formats=["%D.%m.%Y %H:%M"]),
)
super(CustomDateTimeRangeField, self).__init__(fields, *args, **kwargs)
From here, you can either create a separate class, or override the field_class
for all DateTimeFromToRangeFilter
s.
class CustomDateTimeFromToRangeFilter(django_filters.RangeFilter):
field_class = CustomDateTimeRangeField
# or
django_filters.DateTimeFromToRangeFilter.fields_class = CustomDateTimeRangeField