Daterange with two inputs date_from and dato_to?

3,530 views
Skip to first unread message

Rastislav Kober

unread,
Aug 18, 2013, 2:31:08 PM8/18/13
to django...@googlegroups.com
Hello

How to do DateRangeFilter with two inputs 'date from' and 'dato to'? 

I read docs and search forum, but I don't find anything.

Any ideas would be appreciated.

Thanks in advance

Rasto

Tim Zenderman

unread,
Aug 21, 2013, 12:08:01 PM8/21/13
to django...@googlegroups.com
I had this same issue and couldn't figure out how to get the job done. I ended up subclassing the DateRangeFilter (similar to the admin daterange filter) and overriding `options` so I could add a handful more. I don't love that implementation and neither do our users. I was going to invest a bit more time later to make it work the way you are describing, but my initial ideas were to make two separate fields for 'from' and 'to' and assign an `action` to each where they filter accordingly. Probably, a better way would be to create a django `MultiWidget`, but I've never made one, so I'm not sure...

Let me know if you figure something out!

Rastislav Kober

unread,
Aug 30, 2013, 2:37:06 AM8/30/13
to django...@googlegroups.com
I write  filter_extra.py for date range filter

from django import forms
from django_filters import Filter
import datetime


class DateRangeWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        attrs_from = {'class': 'date-from'}
        attrs_to = {'class': 'date-to'}

        if attrs:
            attrs_from.update(attrs)
            attrs_to.update(attrs)

        widgets = (forms.TextInput(attrs=attrs_from), forms.TextInput(attrs=attrs_to))
        super(DateRangeWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return [value.start, value.stop]
        return [None, None]

    def format_output(self, rendered_widgets):
        return '<div class="date-range">' + ' - '.join(rendered_widgets) + '</div>'


class DateRangeField(forms.MultiValueField):
    widget = DateRangeWidget

    def __init__(self, *args, **kwargs):
        fields = (
            forms.DateField(),
            forms.DateField(),
        )
        super(DateRangeField, self).__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return slice(*data_list)
        return None


class DateRangeFilter(Filter):
    field_class = DateRangeField

    def filter(self, qs, value):
        date_start = datetime.datetime.combine(value.start, datetime.time(0, 0, 0))
        date_stop = datetime.datetime.combine(value.stop, datetime.time(23, 59, 59))

        if value:
            lookup = '%s__range' % self.name
            return qs.filter(**{lookup: (date_start, date_stop)})
        return qs

then in filters.py:

class SomeFilter(django_filters.FilterSet):
    date = filter_extra.DateRangeFilter(label='Date Range')

for Javascript I use bootstrap datepicker from https://github.com/dangrossman/bootstrap-daterangepicker

and then in JS something like this

    // Date Range Filter - Start
    $('.date-range').each(function(i, el) {
        $(el).find('input').daterangepicker(
            {
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
                    'Last 7 Days': [moment().subtract('days', 6), moment()],
                    'Last 30 Days': [moment().subtract('days', 29), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
                },
                startDate: moment().subtract('days', 29),
                endDate: moment()
            },
            function(start, end) {
                $(el).find('.date-from').val(start.format('MM/DD/YYYY'));
                $(el).find('.date-to').val(end.format('MM/DD/YYYY'));
            }
        );
    });
    // Date Range Filter - End


may by help

Rasto


Dňa streda, 21. augusta 2013 18:08:01 UTC+2 Tim Zenderman napísal(-a):

Tim Zenderman

unread,
Aug 30, 2013, 11:33:21 AM8/30/13
to django...@googlegroups.com
Ratislav, thanks a ton for these snippets. Looks very promising, looking into it over the weekend.

-Tim


--
You received this message because you are subscribed to a topic in the Google Groups "django-filter" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-filter/lbi_B4zYq4M/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-filte...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Lynn Hong

unread,
Jul 22, 2015, 3:33:07 AM7/22/15
to django-filter
Wow thanks a lot!!! You're my hero Ratislav.....

- Lynn

Deepa Mathur

unread,
Oct 1, 2019, 6:34:51 AM10/1/19
to django-filter
'DateRangeFilter' object has no attribute 'name'
I have this problem

Deepa Mathur

unread,
Oct 1, 2019, 7:53:53 AM10/1/19
to django-filter
'DateRangeFilter' object has no attribute 'name'



Reply all
Reply to author
Forward
0 new messages