Hi
how can i add a date filter in django admin panel?
imagine this is my model:
class MyModel(models.Model):
name = ....
created = ....
i need a custom filter in django admin panel that takes any date and returns all the model instance that created equals to input date.
I’m using django 3.2 an sadly default behaviour is not what i want as i add created to the list_filters
How is the default behavior not working as you want?
If you can’t get that to work as desired, then your next-best option is probably a custom search_fields
query.
i mean when i add created into list_filter because of lookups method it only shows some option to choose (like today or past 7 days) as you see in the picture:
but i want somthing like this:
(i’m working on it now)
this is the actual code (i don’t know if it is the best practise):
class RepeatedDemandDateFilter(admin.SimpleListFilter):
title = _('Repeated Demand Date')
parameter_name = 'repeated_demand__created'
template = 'admin/input_filter.html'
def lookups(self, request, model_admin):
return (),
def choices(self, changelist):
all_choice = next(super().choices(changelist))
all_choice['query_parts'] = (
(k, v)
for k, v in changelist.get_filters_params().items()
if k != self.parameter_name
)
yield all_choice
def queryset(self, request, queryset):
date_value = request.GET.get(self.parameter_name)
if date_value:
try:
filter_date = datetime.strptime(date_value, '%Y-%m-%d').date()
return queryset.filter(**{f"{self.parameter_name}__date": filter_date}).distinct()
except ValueError:
return queryset
return queryset
here is the input_filter.html
{% load i18n %}
<h3>{% blocktrans with filter_title=title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul>
<li>
{% with choices.0 as all_choice %}
<form method="GET" action="">
{% for k, v in all_choice.query_parts %}
<input type="hidden" name="{{ k }}" value="{{ v }}" />
{% endfor %}
<input type="date"
value="{{ spec.value|default_if_none:'' }}"
name="{{ spec.parameter_name }}" style="margin-right: 20px;"/>
<button type="submit" class="button" style="width: 100px; height: 40px; padding: 10px 20px; font-size: 12px;">filter</button>
{% if not all_choice.selected %}
<strong><a href="{{ all_choice.query_string }}">x {% trans 'Remove' %}</a></strong>
{% endif %}
</form>
{% endwith %}
</li>
</ul>