Using AutocompleteSelect in a Django Admin form
I was building an action for a Django Admin changelist
view to allow associating models to a related model. But to select the related model on the form, a regular ModelChoiceField
would load all of the possibilities to populate the <select>
form field, which was pretty terrible when there are thousands to tens of thousands of options.
Within the change
view of the model, you can just add that field to autocomplete_fields
and Django has a nice built-in widget that uses a Select2-style form input. It is called AutocompleteSelect
. I couldn't find any examples of someone using this widget outside of it being pulled in by autocomplete_fields
but it ended up being surprisingly easy.
Here is a rough example of the form definition at the heart of the solution:
from django import forms
from django.contrib.admin.widgets import AutoCompleteSelect
from .models import Model, RelatedModel
class BatchAssociationForm(forms.Form):
related_field = forms.ModelChoiceField(
queryset=RelatedModel.objects.all(),
label="Related",
help_text="Select the object to relate to",
widget=AutocompleteSelect(Model.related_field.field, admin.site)
)
No extra package necessary. I am using Django 5.2, and I have no idea if this will work with earlier versions.
A while back, I wanted to build a filter for a changelist
admin that used the autocomplete widget for selecting the value(s) to filter on. Now that I cracked it for a form, maybe I should revisit that idea.