How to add limitations to a RelatedFieldMixin
PaleNeutron opened this issue · comments
Goal
As we know,when we use default autocomplete_fields
, widget, it get's result by target Admin's get_search_results
method.
Problem
But when we use select2 provided Field, it will load all choice at the very beginning and just call field's limit_choices_to
query. Thus, we have no way to limit result by current request info.
Code Snippet
Please provide a code snippet of your problem.
Hey @PaleNeutron,
thanks for reaching out. So what you are looking for should be possible. If I understand you correctly, you want to create a select input, where you are using the request
information, like request.user
to alter the select options.
This isn't possible with the current Django implementation of autocomplete_fields
in fact not even limit_choices_to
is. However, this patch will make it possible, to don't forget to 👍 it django/django#11026
So to make this possible, please follow the documentation and setup a regular Select2 field in the admin. The documentation should help you out. Once that is working, you need to override the filter_queryset
method of your widget.
django-select2/django_select2/forms.py
Lines 391 to 407 in 39ab326
As you see, the method receives the request as well as the default queryset. Whatever you return in this method, will be used to render the options.
Let me know if you have any trouble.
Best
-Joe