How to filter choices in Django2's autocomplete_fields?

800 views
Skip to first unread message

Oren

unread,
Jan 8, 2018, 11:49:56 AM1/8/18
to Django users

In Django 2.0, autocomplete_fields was added, which is great.

Without autocomplete_fields, I can change the queryset of a ForeignKeyField using formfield_for_foreignkey.

But combining the two together doesn't work - it looks like the list of options for autocomplete is dynamic and coming from a different url, instead of from the current form.

So the question is -

How can I change the queryset in the autocomplete widget?

Thanks,
Oren

ciaran....@activeenergy.ie

unread,
Aug 29, 2018, 8:55:38 AM8/29/18
to Django users
You need to override  ModelAdmin.get_search_results()  as per https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields

My problem is I override ForeignKeyField in AdminForm, where I can filter based on self.instance, this is not possible in current implementation AFAICS? The instance ID would have to be passed to the autocomplete_view

ciaran....@activeenergy.ie

unread,
Aug 29, 2018, 9:11:51 AM8/29/18
to Django users
Not possible ATM it seems, pity https://code.djangoproject.com/ticket/29010
Reply all
Reply to author
Forward
0 new messages