Django filters update query when user changes value in dropdown filter

Viewed 612

I have a filter that is for my model that is a select of all the values in that columns. I would like to make it so that when the user select a value from the select it automatically filters the data without the need for a submit button. I believe I need an onclick attribute for the select field but I cant figure out how to set that up for filter forms.

filters.py

import django_filters
from django_filters import CharFilter, AllValuesFilter

from .models import *


class SetFilter(django_filters.FilterSet):
    name = CharFilter(field_name='name', lookup_expr='icontains', label='', )
    type = AllValuesFilter(field_name='type', choices=Set.objects.values_list('type', flat=True).distinct(), label='', )

    class Meta:
        model = Set
        fields = ''
        exclude = ['']

sets.html:

<td class="d-none d-xl-table-cell">{{ myFilter.form.type }}</td>
1 Answers

you need to use jquery or pure Javascript to react on user actions. here is code with jQUERY

$(document).ready(function() {
    $('#id_type').bind('change', function(event) {
        $('#you_form_id').trigger("submit");
    });
});

here we check when user changes field type and then automatically submit filter form

Related