Skip to content

Commit

Permalink
Add DateRangeQuickSelectListFilter, which is a mix of admin.DateField…
Browse files Browse the repository at this point in the history
…ListFilter and DateRangeFilter
  • Loading branch information
robertpro committed Aug 18, 2023
1 parent 61e52fa commit 4358001
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
36 changes: 36 additions & 0 deletions rangefilter/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,3 +403,39 @@ def NumericRangeFilterBuilder(title=None, default_start=None, default_end=None):
)

return filter_cls


class DateRangeQuickSelectListFilter(admin.DateFieldListFilter, DateRangeFilter):
template = 'rangefilter/date_range_quick_select_list_filter.html'

def expected_parameters(self):
params = [self.lookup_kwarg_gte, self.lookup_kwarg_lte]
if self.field.null:
params.append(self.lookup_kwarg_isnull)
return params

def _make_query_filter(self, request, validated_data):
query_params = super()._make_query_filter(request, validated_data)
date_value_gte = validated_data.get(self.lookup_kwarg_gte, None)
date_value_lte = validated_data.get(self.lookup_kwarg_lte, None)
date_value_isnull = validated_data.get(self.lookup_kwarg_isnull, None)

if date_value_isnull is not None and not any([date_value_lte, date_value_gte]):
query_params[self.lookup_kwarg_isnull] = date_value_isnull

return query_params

def _get_form_fields(self):
fields = super()._get_form_fields()
if self.field.null:
fields.update(OrderedDict(
(
(self.lookup_kwarg_isnull, forms.BooleanField(
label='',
localize=True,
required=False,
widget=forms.HiddenInput,
)),
)
))
return fields
1 change: 1 addition & 0 deletions rangefilter/templates/rangefilter/date_filter.html
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ <h3>{{ title }}</h3>
}
});
</script>
{% block quick-select-choices %}{% endblock %}
<div class="admindatefilter">
<form method="GET" action="." id="{{ choices.0.system_name }}-form">
{{ spec.form.as_p }}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{% extends 'rangefilter/date_filter.html' %}

{% block quick-select-choices %}
{% comment %}
The following code under the <ul> tag belongs to admin/filter.html:
https://github.com/django/django/blob/stable/2.2.x/django/contrib/admin/templates/admin/filter.html#L3-L8
{% endcomment %}
<ul>
{% for choice in choices %}
<li{% if choice.selected %} class="selected"{% endif %}>
<a href="{{ choice.query_string|iriencode }}"
title="{{ choice.display }}">{{ choice.display }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}

0 comments on commit 4358001

Please sign in to comment.