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

时间:2018-01-30 03:37:03

标签: django wagtail

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

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)几乎就是我所追求的,但我不确定在创建文章本身之前如何检索父页面的组?

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

1 个答案:

答案 0 :(得分:2)

不幸的是,我不知道limit_choices_to函数接收父对象引用的方法。您的第二个链接位于正确的轨道上,我们需要为页面提供自己的基本表单,并调整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有2个主要属性grouppagerelated_name的{​​{1}}外键的group定义为GroupPagePermission,并且每次与page_permissions一样创建ForeignKey时,它实际上创建了一个名为page的字段。因此,我们可以遵循关系,并使用父类别页面的ID按page_id过滤组。