Add custom ranges to litepicker

This commit is contained in:
Paweł Jastrzębski 2021-04-22 15:57:19 +02:00
parent 2c0fafefea
commit faf4f48e75
2 changed files with 60 additions and 0 deletions

View File

@ -1,3 +1,5 @@
import json
from datetime import datetime, time
from urllib.parse import urlparse
@ -23,8 +25,56 @@ class DateRangeMixin:
else:
return timezone.now()
def get_date_ranges(self):
now = timezone.now()
return [
{'name': 'Today', 'start': now, 'end': now},
{
'name': 'Yesterday',
'start': now - timezone.timedelta(days=1),
'end': now - timezone.timedelta(days=1),
},
{
'name': 'Last 7 days',
'start': now - timezone.timedelta(days=7),
'end': now,
},
{
'name': 'Last 30 days',
'start': now - timezone.timedelta(days=30),
'end': now,
},
{
'name': 'Last 90 days',
'start': now - timezone.timedelta(days=90),
'end': now,
},
{
'name': 'This month',
'start': now.replace(day=1),
'end': now,
},
{
'name': 'Last month',
'start': now.replace(day=1, month=now.month - 1),
'end': now.replace(day=1, month=now.month) - timezone.timedelta(days=1),
},
{
'name': 'This year',
'start': now.replace(day=1, month=1),
'end': now,
},
{
'name': 'Last year',
'start': now.replace(day=1, month=1, year=now.year - 1),
'end': now.replace(day=1, month=1) - timezone.timedelta(days=1),
},
]
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data["start_date"] = self.get_start_date()
data["end_date"] = self.get_end_date()
data["date_ranges"] = self.get_date_ranges()
return data

View File

@ -24,6 +24,16 @@
maxDate: new Date(),
startDate: Date.parse(document.getElementById("startDate").getAttribute("value")),
endDate: Date.parse(document.getElementById("endDate").getAttribute("value")),
ranges: {
customRanges: {
{% for date_range in date_ranges %}
'{{ date_range.name }}': [
new Date('{{ date_range.start.isoformat }}'),
new Date('{{ date_range.end.isoformat }}')
],
{% endfor %}
}
}
});
picker.on('selected', (startDate, endDate) => {
document.getElementById("startDate").setAttribute("value", startDate.getFullYear() +