From 2f2b9345afdd9c2a156071394da86994cd08cd9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 11 Feb 2022 21:32:32 -0300 Subject: [PATCH] =?UTF-8?q?Cria=C3=A7=C3=A3o=20do=20DateRangeFilter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/utils/filters.py | 42 ++++++++++++++++++- .../templates/admin/date_range_filter.html | 13 ++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 sigi/apps/utils/templates/admin/date_range_filter.html diff --git a/sigi/apps/utils/filters.py b/sigi/apps/utils/filters.py index faf0c7f..1b1034b 100644 --- a/sigi/apps/utils/filters.py +++ b/sigi/apps/utils/filters.py @@ -1,5 +1,6 @@ import string from math import log10 +from django import forms from django.contrib import admin from django.contrib.admin.options import IncorrectLookupParameters from django.utils.translation import ngettext, gettext as _ @@ -132,4 +133,43 @@ class RangeFilter(admin.FieldListFilter): except (ValueError, ValidationError) as e: raise IncorrectLookupParameters(e) - return queryset \ No newline at end of file + return queryset + +class DateRangeFilter(admin.FieldListFilter): + template = 'admin/date_range_filter.html' + def __init__(self, field, request, params, model, model_admin, field_path): + self.model = model + self.model_admin = model_admin + self.lookup_kwargs = [f'{field_path}__gte', f'{field_path}__lte'] + + super().__init__(field, request, params, model, model_admin, field_path) + + form = self.get_date_form(self.used_parameters) + if form.is_valid(): + self.used_parameters = { + key: value for key,value in form.cleaned_data.items() + if value is not None + } + else: + self.used_parameters = {} + + def has_output(self): + return self.model.objects.exists() + + def expected_parameters(self): + return self.lookup_kwargs + + def choices(self, changelist): + return [{ + 'query_string': changelist.get_query_string( + remove=self.lookup_kwargs), + 'form': self.get_date_form(self.used_parameters) + }] + + def get_date_form(self, context={}): + date_fields = {name: forms.DateField(required=False) + for name in self.lookup_kwargs} + DateForm = type('DateForm', (forms.Form,), date_fields) + + return DateForm(context) + diff --git a/sigi/apps/utils/templates/admin/date_range_filter.html b/sigi/apps/utils/templates/admin/date_range_filter.html new file mode 100644 index 0000000..c3ee1ec --- /dev/null +++ b/sigi/apps/utils/templates/admin/date_range_filter.html @@ -0,0 +1,13 @@ +{% load i18n %} +{% with choice=choices.0 %} +
+
+ + + {% trans 'All' %} + {% for field in choice.form %} + + {% endfor %} +
+
+{% endwith %} \ No newline at end of file