applegrew / django-select2

This is a Django integration for Select2
MIT License
710 stars 316 forks source link

How to add limitations to a RelatedFieldMixin #590

Closed PaleNeutron closed 4 years ago

PaleNeutron commented 4 years ago

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.

codingjoe commented 4 years ago

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 https://github.com/django/django/pull/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. https://github.com/applegrew/django-select2/blob/39ab326884c5bcb84f534a883aa204089c19dd53/django_select2/forms.py#L391-L407 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