Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wagtail: Filter results of an InlinePanel ForeignKey

Tags:

django

wagtail

These models allow me to establish multiple human "editors" for a tool:

class ToolPageEditors(models.Model):
    person = models.ForeignKey('people.UserProfile')
    page = ParentalKey('ToolPage', related_name='toolpage_editors')


class ToolPage(BaseAsset):
    content_panels = BaseAsset.content_panels + [
        InlinePanel('toolpage_editors', label="Tool Editors")
    ]

But then each ToolPageEditors instance is a dropdown with more than 3,000 users. I'd like to limit the contents of that dropdown to people in a given group. I know how to do this in Django by overriding the admin form, but am having trouble figuring out how to accomplish it in Wagtail.

Suggestions? Thanks.

Update:

The key is limit_choices_to. Modified the class as follows and it works:

class ToolPageManagers(models.Model):
    def get_tool_editors():
        g = Group.objects.get(name='Tool Editors')
        return {'groups__in': [g, ]}

    person = models.ForeignKey('people.UserProfile',  limit_choices_to=get_tool_editors)
    page = ParentalKey('ToolPage', related_name='toolpage_editors')
like image 746
shacker Avatar asked Nov 11 '16 18:11

shacker


1 Answers

Answer was put as an update to the original question, pasted below with some docs links.

You can limit the available choices on a Django model's foreign key relationship by the kwarg limit_choices_to.

Note: this will add a limit to the relationship, not just the choices available in the UI.

Example code

class ToolPageManagers(models.Model):
    def get_tool_editors():
        g = Group.objects.get(name='Tool Editors')
        return {'groups__in': [g, ]}

    person = models.ForeignKey('people.UserProfile',  limit_choices_to=get_tool_editors)
    page = ParentalKey('ToolPage', related_name='toolpage_editors')

For more information about Wagtail's InlinePanel see the Wagtail docs - https://docs.wagtail.io/en/latest/reference/pages/panels.html#inline-panels

like image 123
LB Ben Johnston Avatar answered Nov 05 '22 21:11

LB Ben Johnston