PHACDataHub / django-htmx-autocomplete

A Django autocomplete component powered by htmx
MIT License
49 stars 4 forks source link

How to populate get_items with a dynamic subset. #59

Open Nielssie opened 4 days ago

Nielssie commented 4 days ago
@staticmethod
def autocomplete_school_items(search=None, values=None):
    schools = School.active_objects.all()
    items = None
    if search is not None:
        items = schools.filter(search_field__icontains=search)
    if values is not None:
        items = schools.filter(id__in=values)
    return [{"label": x.search_field, "value": x.id} for x in items]

class SchoolListForm(HelperFormMixin, forms.Form):

    school = forms.CharField(
        required=True,
        widget=Autocomplete(
            name="school",
            options=dict(
                multiselect=False,
                get_items=autocomplete_school_items,
                minimum_search_length=0,
            ),
        ),
    )

    def __init__(self, *args, **kwargs):
        self.schools = kwargs.pop("schools", None)

        super().__init__(*args, **kwargs)

        layout_array = [
            "school",
        ]

        self.helper.layout = Layout(*layout_array)

In the current code get_items comes from a (deprecated) static method.

I want to populate the get_items with a subset (self.schools). The subset is created in the View and user dependent Any ideas?

juleskuehn commented 4 hours ago

Sure! See the discussion here: https://github.com/PHACDataHub/django-htmx-autocomplete/discussions/58

This is a common issue with the library and we want to make it easier to use dynamic querysets in a "v2" of the library.

If it is just user dependent, you can use a middleware helper or library (https://github.com/AlexCLeduc/django-data-fetcher) to get the current request. Then in the get_items method, create your subset of schools based on the request.user. No need to create the subset in the View.