Then autocomplete view for country selection will be similar to next
fromyour_countries_app.modelsimportCountryclassCountryAutocomplete(autocomplete.Select2QuerySetView):defget_queryset(self):# Don't forget to filter out results depending on the visitor !ifnotself.request.user.is_authenticated():returnCountry.objects.none()qs=Country.objects.all()ifself.q:qs=qs.filter(name__istartswith=self.q)returnqs
fromdjango.contribimportadminfromyour_countries_app.modelsimportCountry,Personfromdal_admin_filtersimportAutocompleteFilter@admin.register(Country)classCountryAdmin(admin.ModelAdmin):passclassCountryFilter(AutocompleteFilter):title='Country from'# filter's titleparameter_name='from_country'# field name - ForeignKey to Country modelautocomplete_url='country-autocomplete'# url name of Country autocomplete viewclassCountryPlaceholderFilter(AutocompleteFilter):title='Country from'# filter's titleparameter_name='from_country'# field name - ForeignKey to Country modelautocomplete_url='country-autocomplete'# url name of Country autocomplete viewis_placeholder_title=True# filter title will be shown as placeholder@admin.register(Person)classPersonAdmin(admin.ModelAdmin):classMedia:# Empty media class is required if you are using autocomplete filterpass# If you know better solution for altering admin.media from filter instance# - please contact me or make a pull requestlist_filter=[CountryFilter]
If setup is done right, you will see the Select2 widget in admin filter
in Person’s changelist view.