Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

Limit queryset on Django 2 autocomplete_field

For a long time we've been overriding our ModelAdmin's formfield_for_foreignkey to limit the queryset the field can choose from. Here's a simplified version of what I mean:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "site":
        if not request.user.is_superuser:
            kwargs["queryset"] = request.user.site

But I recently added this field to the autocomplete_fields definition (to get some Select2 gravy). The result was I now see no suggestions as a non-superuser account.

Is there a more right way to limit the queryset, or is this a simple bug in Django?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This needs a patch that's still in dev. You can be patient, or you can monkey-patch AutocompleteJsonView.has_perm as I am below. I just stuck this in settings.

If you're also stuck on 2.0.x (as I currently am shakes fist at Wagtail) you'll also need to make sure your ModelAdmins define a has_view_permission.

from django.contrib.admin.views.autocomplete import AutocompleteJsonView
def ac_has_perm(self, request, obj=None):
    return self.model_admin.has_view_permission(request, obj=obj)
AutocompleteJsonView.has_perm = ac_has_perm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...