I want to add custom range of date like, in my start date I don’t want to select future date it should be less than or equal to today.
class PartLogFilter(django_filters.FilterSet):
transaction_time = django_filters.DateRangeFilter(
label='Transaction Time', widget=forms.RadioSelect, null_value=None
)
date_range = django_filters.DateFromToRangeFilter(
label='By Date Range',
method='filter_by_range',
widget=RangeWidget(attrs={'class': 'datepicker', 'type': 'date'})
)
class Meta:
model = PartLog
fields = ['transaction_time', 'date_range']
def filter_by_range(self, queryset, name, value):
start = value.start
end = value.stop
return queryset.filter(transaction_time__gte=start, transaction_time__lte=end)
My front end:
<div class="filters-div parts-report-filter">
<form method="get" style="border:1px solid black">
<p class="filters-header">FILTER</p>
{{ filter.form.as_p }}
<button type="submit" id="submit-filter" style="visibility: hidden; height: 1px">Filter</button>
</form>
</div>
{% block js_load %}
{{ block.super }}
{% endblock %}
{% block js_ready %}
{{ block.super }}
$('#id_time_0').attr("text", "From");
$('#id_time_1').attr("text", "To");
$('.datepicker').first().on("change", function (e) {
if($('.datepicker').last().val()) {
$('#submit-filter').click();
}
});
$('.datepicker').last().on("change", function (e) {
if($('.datepicker').first().val()) {
$('#submit-filter').click();
}
});
{% endblock %}
My Views.py:
class LogPartExport(AjaxView):
model = PartLog
def get(self, request, *args, **kwargs):
export_format = request.GET.get('format', 'xls').lower()
if export_format not in GetExportFormats():
export_format = 'xls'
filename = 'InvenTree_part_reports_{date}.{fmt}'.format(
date=datetime.now(),
fmt=export_format
)
transaction_time = request.GET.get('transaction_time')
date_range_start = request.GET.get('date_range_min')
date_range_end = request.GET.get('date_range_max')
filters = {
'today': {
'transaction_time__year': now().year,
'transaction_time__month': now().month,
'transaction_time__day': now().day
},
'yesterday': {
'transaction_time__year': (now() - timedelta(days=1)).year,
'transaction_time__month': (now() - timedelta(days=1)).month,
'transaction_time__day': (now() - timedelta(days=1)).day,
},
'week': {
'transaction_time__gte': _truncate(now() - timedelta(days=7)),
'transaction_time__lt': _truncate(now() + timedelta(days=1)),
},
'month': {
'transaction_time__year': now().year,
'transaction_time__month': now().month
},
'year': {
'transaction_time__year': now().year,
},
}
part_logs = PartLog.objects.all()
if transaction_time:
part_logs = part_logs.filter(**filters[transaction_time])
if date_range_start and date_range_end:
part_logs = part_logs.filter(transaction_time__gte=date_range_start,
transaction_time__lte=date_range_end)
dataset = PartLogResource().export(queryset=part_logs)
filedata = dataset.export(export_format)
ReportHistory.submit(user=request.user, report_name=filename)
return DownloadFile(filedata, filename)