Search code examples
django-formsdjango-widgetdjango-filters

How to set different placeholders for DateFromToRangeFilter?


I am using django_filters in my project and one of them is a DateFromToRangeFilter. This filter generates two input fields in your templates, figuratively - 'From' and 'To'.

There is no problem to set a similar attribute for these fields. For example:

end = django_filters.DateFromToRangeFilter(
        widget=django_filters.widgets.RangeWidget(
                attrs={'placeholder': 'yyyy-mm-dd'}))

But I cannot understand how to set different placeholders (or any other attributes for each of the fields). Like 'Enter the start date' for field 'From' and 'Enter the finish date' for field "To".

Can someone help?


Solution

  • By default MultiWidget passes all attrs to each subwidget. To bypass this, you would have to subclass RangeWidget and provide separate attrs parameters for each of the from/to widgets.

    Something like the following:

    class MyRangeWidget(RangeWidget):
        def __init__(self, from_attrs=None, to_attrs=None, attrs=None):
            super(MyRangeWidget, self).__init__(attrs)
    
            if from_attrs:
                self.widgets[0].attrs.update(from_attrs)
            if to_attrs:
                self.widgets[1].attrs.update(to_attrs)