'how to pass context (placeholder in my case) to django admin Simple List filter
I am creating a college management system with facility to store quiz/tests in the website and get student performance. I wanted to filter quiz based on month year, such as show all quiz of march 2022.
For this purpose, I can not show all months and years in the sidebar, its useless for the first, second it will take lot of space and client has to scroll a lot.
So I created a custom Simple Text Input by following some blogs. Here is that generic filter code:
class SimpleTextInputFilter(admin.SimpleListFilter):
template = 'admin/input_filter.html'
def filter(self, request, queryset, value):
raise NotImplementedError('Implement this method in subclasses.')
def queryset(self, request, queryset):
if self.value() is not None:
return self.filter(request, queryset, self.value())
def lookups(self, *args, **kwargs):
return None
def has_output(self):
return True
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
And here is how I am using it:
class QuizMonthYearFilter(SimpleTextInputFilter):
parameter_name = 'date'
title = 'Quiz (Month Year)'
def filter(self, request, queryset, value):
try:
date = datetime.strptime(value, '%b %Y')
except:
pass
else:
return queryset.filter(date__year=date.year, date__month=date.month)
and admin/input_filter.html is:
{% 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="text"
value="{{ spec.value|default_if_none:'' }}"
name="{{ spec.parameter_name }}"
placeholder={{ **GET VALUE HERE** }}/>
{% if not all_choice.selected %}
<strong><a href="{{ all_choice.query_string }}">x {% trans 'Remove' %}</a></strong>
{% endif %}
</form>
{% endwith %}
</li>
</ul>
Now I want to pass placeholder to the input of the filter. So I want to pass context data to the html template, please suggest me how I can do that, so that I can give user hint about the date format.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
