Browse Source

Criação do DateRangeFilter

revisaoSidenav
Sesostris Vieira 3 years ago
parent
commit
2f2b9345af
  1. 42
      sigi/apps/utils/filters.py
  2. 13
      sigi/apps/utils/templates/admin/date_range_filter.html

42
sigi/apps/utils/filters.py

@ -1,5 +1,6 @@
import string import string
from math import log10 from math import log10
from django import forms
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.options import IncorrectLookupParameters
from django.utils.translation import ngettext, gettext as _ from django.utils.translation import ngettext, gettext as _
@ -132,4 +133,43 @@ class RangeFilter(admin.FieldListFilter):
except (ValueError, ValidationError) as e: except (ValueError, ValidationError) as e:
raise IncorrectLookupParameters(e) raise IncorrectLookupParameters(e)
return queryset 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)

13
sigi/apps/utils/templates/admin/date_range_filter.html

@ -0,0 +1,13 @@
{% load i18n %}
{% with choice=choices.0 %}
<div class="col s12">
<form method="get" action="{{ choice.query_string|iriencode }}">
<label>{% blocktrans with filter_title=title %} By {{ filter_title }} {% endblocktrans %}</label>
<button class="btn-floating btn-small right pulse waves-effect waves-light" type="submit"><i class="material-icons tiny">send</i></button>
<a href="{{ choice.query_string|iriencode }}">{% trans 'All' %}</a>
{% for field in choice.form %}
<input id="{{ field.id }}" name="{{ field.name }}" type="text" class="datepicker" value="{{ field.value|default_if_none:''|date:"SHORT_DATE_FORMAT" }}"/>
{% endfor %}
</form>
</div>
{% endwith %}
Loading…
Cancel
Save