Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to populate get_items with a dynamic subset. #59

Open
Nielssie opened this issue Oct 3, 2024 · 1 comment
Open

How to populate get_items with a dynamic subset. #59

Nielssie opened this issue Oct 3, 2024 · 1 comment

Comments

@Nielssie
Copy link

Nielssie commented Oct 3, 2024

@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
Copy link
Contributor

juleskuehn commented Oct 7, 2024

Sure! See the discussion here: #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants