How can I return a queryset for a fk or m2m field in wagtail admin create form?

醉酒当歌 提交于 2020-03-26 03:06:05

问题


My question holds for any wagtail panel that returns select options from a foreignkey or M2M relationship, like a PageChooserPanel or SnippetChooserPanel.

How can I filter the list of options server-side, for the user to only see the information he has access to?

I have a Plan model. When creating a new plan, I would like request.user to only see the list of companies he is affiliated to.

from modelcluster.models import ClusterableModel
from wagtailautocomplete.edit_handlers import AutocompletePanel


class Plan(ClusterableModel):
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        blank=True,
    )
    company = models.ForeignKey(
        "home.HomePage", on_delete=models.PROTECT,
    )

    edit_panels = [
        AutocompletePanel("company", target_model="company.Company"),
    ]


class PlanAdmin(ModelAdmin):
    model = Plan

    def get_queryset(self, request: HttpRequest) -> QuerySet:
        qs = super().get_queryset(request)
        if request.user.is_staff or request.user.is_superuser:
            return qs
        # Only show plans for the current user
        return qs.filter(created_by=request.user)

Currently, my "company" panel will return all companies existing in the database. I would like to only display companies that are in relation to the request current user, information that I can get with request.user.get_companies() (returns a Company queryset).

Wagtail-style, I thought that a Panel could have some property to set a queryset. Or maybe some ModelAdmin method. Django-style, I would do that in the form. Since I cannot figure this problem out wagtail-style, I'll investigate how to do the job with a custom form set in a custom CreateView added to PlanAdmin.create_view_class

Related: github question to Wagtail-autocomplete

来源:https://stackoverflow.com/questions/57552920/how-can-i-return-a-queryset-for-a-fk-or-m2m-field-in-wagtail-admin-create-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!