Wagtail:获取具有特定权限(编辑、删除)的父页组

Wagtail: get parent page groups that have specific rights (edit, delete)

我在 wagtail 中有一个类别页面 -> 文章页面层次结构。文章页面有作者字段,显示当前系统所有用户。我想根据父类别页面的组来过滤文章的作者。

models.py

from django.contrib.auth.models import Group

class CategoryPage(Page):  # query service, api
    blurb = models.CharField(max_length=300, blank=False)
    content_panels = Page.content_panels + [
        FieldPanel('blurb', classname="full")
    ]
    subpage_types = ['cms.ArticlePage']


class ArticlePage(Page):  # how to do X with query service
    ...
    author = models.ForeignKey(User, on_delete=models.PROTECT, default=1,
                           # limit_choices_to=get_article_editors,
                           help_text="The page author (you may plan to hand off this page for someone else to write).")

def get_article_editors():
    # get article category
    # get group for category
    g = Group.objects.get(name='??')
    return {'groups__in': [g, ]}

This question (limit_choices_to) 几乎是我所追求的,但我不确定如何在文章本身创建之前检索父页面的组?

似乎可以在创建时访问父页面,但我仍然不确定如何找到可以编辑父页面的组。

不幸的是,我不知道 limit_choices_to 函数接收对父对象的引用的方法。您的第二个 link 在正确的轨道上,我们需要向页面提供我们自己的基本表单并调整 author 字段的查询集。

from django.contrib.auth.models import Group
from wagtail.wagtailadmin.forms import WagtailAdminPageForm
from wagtail.wagtailcore.models import Page


class ArticlePageForm(WagtailAdminPageForm):
    def __init__(self, data=None, files=None, parent_page=None, *args, **kwargs):
        super().__init__(data, files, parent_page, *args, **kwargs)

        # Get the parent category page if `instance` is present, fallback to `parent_page` otherwise.
        # We're trying to get the parent category page from the `instance` first
        # because `parent_page` is only set when the page is new (haven't been saved before).
        instance = kwargs.get('instance')
        category_page = instance.get_parent() if instance and instance.pk else parent_page
        if not category_page:
            return  # Do not continue if we failed to find the parent category page.

        # Get the groups which have permissions on the parent category page.
        groups = Group.objects.filter(page_permissions__page_id=category_page.pk).distinct()
        if not groups:
            return  # Do not continue if we failed to find any groups.

        # Filter the queryset of the `author` field.
        self.fields['author'].queryset = self.fields['author'].queryset.filter(groups__in=groups)


class ArticlePage(Page):
    base_form_class = ArticlePageForm

关于我们查询组的方式的快速说明: 当你在 Wagtail 中设置页面权限时,你实际上创建了一个 GroupPagePermission,它有两个主要属性,grouppageGroupPagePermissiongroup 的外键的 related_name 被定义为 page_permissions 并且每次你创建一个 ForeignKey 就像 page ,它实际上创建了一个名为 page_id 的字段。因此我们可以按照关系,通过page_permissions__page_id和父类别页面的ID过滤分组。