from djaa_list_filter.admin import AjaxAutocompleteListFilter
from django import forms

class MyAjaxAutocompleteListFilter(AjaxAutocompleteListFilter):
    title = 'list filter'
    template = 'djaa_list_filter/admin/filter/autocomplete_list_filter.html'

    def __init__(self, field, request, params, model, model_admin, field_path):
        model = field.remote_field.model
        super().__init__(field, request, params, model, model_admin, field_path)
        qs_target_value = f'{field_path}__{model._meta.pk.name}__exact'
        queryset = model.objects.get_queryset()
        widget = AjaxAutocompleteSelectWidget(
            model_admin=model_admin, model=model, field=field, field_name=field.remote_field.model._meta.verbose_name, qs_target_value=qs_target_value
        )

        class AutocompleteForm(forms.Form):
            autocomplete_field = forms.ModelChoiceField(queryset=queryset, widget=widget, required=False)
            querystring_value = forms.CharField(widget=forms.HiddenInput())

        autocomplete_field_initial_value = request.GET.get(qs_target_value, None)
        initial_values = dict(querystring_value=request.GET.urlencode())
        if autocomplete_field_initial_value:
            initial_values.update(autocomplete_field=autocomplete_field_initial_value)
        self.autocomplete_form = AutocompleteForm(initial=initial_values, prefix=field.remote_field.model._meta.verbose_name)
        self.title = field.remote_field.model._meta.verbose_name