0

使用 Wagtail 2.9,我正在尝试创建一个具有生成 URL 的功能的块。要生成 URL,我需要当前登录的用户。

class Look(blocks.StructBlock):

    title = blocks.CharBlock(required=True, help_text='Add your look title')
    id = blocks.CharBlock(required=True, help_text='Enter the Id')

    class Meta:
        template = "looker/looker_block.html"
        value_class = LookStructValue

值类的get_url()定义如下:

class LookStructValue(blocks.StructValue):

    def url(self):
        id = self.get('id')

        user = User(15,
                first_name='This is where is need the current user First name',
                last_name='and last name',
                permissions=['some_permission'],
                models=['some_model'],
                group_ids=[2],
                external_group_id='awesome_engineers',
                user_attributes={"test": "test",
                    "test_count": "1"},
                access_filters={})

        url_path = "/embed/looks/" + id 

        url = URL(user,url_path, force_logout_login=True)

        return "https://" + url.to_string()

我可以在 LookStructValue 类中获取当前用户吗?

4

1 回答 1

0

parent_context您可以使用 blocks.Structblock 的get_context方法访问父级的上下文 ( )。

确保使用{% include_block %}.

parent_context 关键字参数在通过{% include_block %}标记呈现块时可用,并且是从调用模板传递的变量的字典。

您必须重新考虑如何创建用户的 URL,而不是将其移动到create_custom_urlUser 模型上的方法(例如:)。

# Basic Example, to point you the right way.

class DemoBlock(blocks.StructBlock):

    title = blocks.CharBlock()

    def get_context(self, value, parent_context=None):
        """Add a user's unique URL to the block's context."""
        context = super().get_context(value, parent_context=parent_context)
        user = parent_context.get('request').user
        context['url'] = user.create_custom_url()
        return context
于 2020-07-10T18:02:38.263 回答