Opened 2 years ago
Closed 2 years ago
#34216 closed Bug (invalid)
django admin when field is autocomplete it overrides ModelForm filter
Reported by: | sahaliyev | Owned by: | nobody |
---|---|---|---|
Component: | contrib.admin | Version: | 4.1 |
Severity: | Normal | Keywords: | autocomplete, filter |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
having issue on django admin. I want one of my foreign key field to be searchable and I achieved that making it autocomplete.
class CollectionAdmin(VersionAdmin, admin.ModelAdmin): form = CollectionForm autocomplete_fields = ["task"]
I also filter that foreign key in ModelForm.
class CollectionForm(forms.ModelForm): class Meta: model = Collection fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.fields.get("task"): self.fields["task"].queryset = self.fields["task"].queryset.filter( status=TaskStatus.ASSIGNED )
When task is not autocomplete field in Collection my filter works as expected. However, when task is autocomplete field in Collection, filter does not work. Instead of my filter in form, task admin get_queryset method is called which is not what I want.
TaskAdmin get_queryset method just filters by user, however I want more filter as you see above, for TaskStatus as well.
def get_queryset(self, request): qs = super().get_queryset(request) if request.user.groups.filter(name=settings.COPYWRITER_GROUP).exists(): return qs.filter(assigned_to=request.user) return qs
Repeating, form init filter works if field is not autocomplete.
I tried removing task from autocomplete of Collection and it worked. I want my form filter not overridden if field is autocomplete.
.queryset
cannot be override for autocomplete fields as it's initialized for every GET request so you need to add custom logic toget_queryset()
. Please use one of support channels where folks should help you implement it differently in your code.