Search code examples
djangowagtailwagtail-streamfield

Getting current user in blocks class in Wagtail


Using Wagtail 2.9, I am trying to create a block that has a function that generates URL. To generate the URL I need the current logged in user.

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

the value class has the get_url() definition which looks like:

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()

Can i get the current user inside the LookStructValue class?


Solution

  • You can access the parent's context (parent_context) using the blocks.Structblock's get_context method.

    Be sure you render the block with {% include_block %}.

    The parent_context keyword argument is available when the block is rendered through an {% include_block %} tag, and is a dict of variables passed from the calling template.

    You'd have to rethink how you were creating the user's URL, instead moving it to a method (example: create_custom_url) on the User model.

    # 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