Filtering rows in the changelist_view method of the admin.ModelAdmin class

Hi, everyone!
I managed to create a form in the admin through which I receive dates. The template is redefined and is located: templates/admin. But I can’t filter the output records like I can do with get_queryset.
In general, I need to: get data from the form and filter the rows in the admin.
How to do this in changelist_view method?

I tried this, but it doesn’t change anything:

qs = Abc.objects.filter(id__gte=3)
response.context_data['cl'].queryset = list(qs)

admin.py


class Abc_Admin(admin.ModelAdmin):
    list_display = ('id',)
    change_list_template = 'admin/change_list.html'

    def changelist_view(self, request, extra_context=None):
        response = super().changelist_view(
            request,
            extra_context=extra_context,
        )

        if request.method != 'POST':
            response.context_data['form'] = TestForm()
        else:
            form = TestForm(request.POST)
            if form.is_valid():
                response.context_data['form'] = form
                val = [form.cleaned_data.get('start'), form.cleaned_data.get('end')]
                qs = Abc.objects.filter(id__gte=3)
                response.context_data['cl'].queryset = list(qs)

                return super().changelist_view(request, extra_context=response.context_data)

        return response

admin.site.register(Abc, Abc_Admin)

template

{% extends 'admin/change_list.html' %}

{% block result_list %}
<form action='' method='POST'>
    {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' value='adding'/>
</form>

{{block.super}}

{% endblock %}

form.py

class TestForm(forms.Form):
    start = forms.DateField(widget=forms.SelectDateWidget(years=range(2022, 2025)))
    end = forms.DateField(widget=forms.SelectDateWidget(years=range(2022, 2025)))

Found a solution: response.context_data['cl'].result_list = list(qs)

1 Like