Python wagtail.core.hooks.get_hooks() Examples

The following are 30 code examples of wagtail.core.hooks.get_hooks(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wagtail.core.hooks , or try the search function .
Example #1
Source File: users.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(request, user_id):
    user = get_object_or_404(User, pk=user_id)

    if not user_can_delete_user(request.user, user):
        return permission_denied(request)

    for fn in hooks.get_hooks('before_delete_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        user.delete()
        messages.success(request, _("User '{0}' deleted.").format(user))
        for fn in hooks.get_hooks('after_delete_user'):
            result = fn(request, user)
            if hasattr(result, 'status_code'):
                return result
        return redirect('wagtailusers_users:index')

    return TemplateResponse(request, "wagtailusers/users/confirm_delete.html", {
        'user': user,
    }) 
Example #2
Source File: views.py    From puput with MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        site = Site.find_for_request(request)
        if not site:
            raise Http404
        if request.resolver_match.url_name == 'entry_page_serve_slug':
            # Splitting the request path and obtaining the path_components
            # this way allows you to place the blog at the level you want on
            # your sitemap.
            # Example:
            # splited_path =  ['es', 'blog', '2016', '06', '23', 'blog-entry']
            # slicing this way you obtain:
            # path_components =  ['es', 'blog', 'blog-entry']
            # with the oldest solution you'll get ['es', 'blog-entry']
            # and a 404 will be raised
            splited_path = strip_prefix_and_ending_slash(request.path).split("/")
            path_components = splited_path[:-4] + splited_path[-1:]
        else:
            path_components = [strip_prefix_and_ending_slash(request.path).split('/')[-1]]
        page, args, kwargs = site.root_page.specific.route(request, path_components)

        for fn in hooks.get_hooks('before_serve_page'):
            result = fn(page, request, args, kwargs)
            if isinstance(result, HttpResponse):
                return result
        return page.serve(request, *args, **kwargs) 
Example #3
Source File: action_menu.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, request, **kwargs):
        self.request = request
        self.context = kwargs
        self.context['user_page_permissions'] = UserPagePermissionsProxy(self.request.user)

        self.menu_items = [
            menu_item
            for menu_item in _get_base_page_action_menu_items()
            if menu_item.is_shown(self.request, self.context)
        ]

        self.menu_items.sort(key=lambda item: item.order)

        for hook in hooks.get_hooks('construct_page_action_menu'):
            hook(self.menu_items, self.request, self.context)

        try:
            self.default_item = self.menu_items.pop(0)
        except IndexError:
            self.default_item = None 
Example #4
Source File: search.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_html(self, request, current=None):
        search_areas = self.search_items_for_request(request)

        # Get query parameter
        form = SearchForm(request.GET)
        query = ''
        if form.is_valid():
            query = form.cleaned_data['q']

        # provide a hook for modifying the search area, if construct_hook_name has been set
        if self.construct_hook_name:
            for fn in hooks.get_hooks(self.construct_hook_name):
                fn(request, search_areas)

        rendered_search_areas = []
        for item in search_areas:
            rendered_search_areas.append(item.render_html(request, query, current))

        return mark_safe(''.join(rendered_search_areas)) 
Example #5
Source File: users.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create(request):
    for fn in hooks.get_hooks('before_create_user'):
        result = fn(request)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_creation_form()(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("User '{0}' created.").format(user), buttons=[
                messages.button(reverse('wagtailusers_users:edit', args=(user.pk,)), _('Edit'))
            ])
            for fn in hooks.get_hooks('after_create_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be created due to errors."))
    else:
        form = get_user_creation_form()()

    return TemplateResponse(request, 'wagtailusers/users/create.html', {
        'form': form,
    }) 
Example #6
Source File: home.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def home(request):

    panels = [
        SiteSummaryPanel(request),
        UpgradeNotificationPanel(request),
        PagesForModerationPanel(request),
        LockedPagesPanel(request),
        RecentEditsPanel(request),
    ]

    for fn in hooks.get_hooks('construct_homepage_panels'):
        fn(request, panels)

    site_details = get_site_for_user(request.user)

    return TemplateResponse(request, "wagtailadmin/home.html", {
        'root_page': site_details['root_page'],
        'root_site': site_details['root_site'],
        'site_name': site_details['site_name'],
        'panels': sorted(panels, key=lambda p: p.order),
        'user': request.user
    }) 
Example #7
Source File: userbar.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def for_frontend(request, page_id):
    items = [
        EditPageItem(Page.objects.get(id=page_id)),
        AddPageItem(Page.objects.get(id=page_id)),
    ]

    for fn in hooks.get_hooks('construct_wagtail_userbar'):
        fn(request, items)

    # Render the items
    rendered_items = [item.render(request) for item in items]

    # Remove any unrendered items
    rendered_items = [item for item in rendered_items if item]

    # Render the edit bird
    return TemplateResponse(request, 'wagtailadmin/userbar/base.html', {
        'items': rendered_items,
    }) 
Example #8
Source File: menus.py    From wagtailmenus with MIT License 6 votes vote down vote up
def get_menu_items_for_rendering(self):
        """
        Return a list of 'menu items' to be included in the context for
        rendering the current level of the menu.

        The responsibility for sourcing, priming, and modifying menu items is
        split between three methods: ``get_raw_menu_items()``,
        ``prime_menu_items()`` and ``modify_menu_items()``, respectively.
        """
        items = self.get_raw_menu_items()

        # Allow hooks to modify the raw list
        for hook in hooks.get_hooks('menus_modify_raw_menu_items'):
            items = hook(items, **self.common_hook_kwargs)

        # Prime and modify the menu items accordingly
        items = self.modify_menu_items(self.prime_menu_items(items))
        if isinstance(items, GeneratorType):
            items = list(items)

        # Allow hooks to modify the primed/modified list
        hook_methods = hooks.get_hooks('menus_modify_primed_menu_items')
        for hook in hook_methods:
            items = hook(items, **self.common_hook_kwargs)
        return items 
Example #9
Source File: forms.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.registered_permissions = Permission.objects.none()
        for fn in hooks.get_hooks('register_permissions'):
            self.registered_permissions = self.registered_permissions | fn()
        self.fields['permissions'].queryset = self.registered_permissions.select_related('content_type') 
Example #10
Source File: groups.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_permission_panel_classes():
    global _permission_panel_classes
    if _permission_panel_classes is None:
        _permission_panel_classes = [GroupPagePermissionFormSet]
        for fn in hooks.get_hooks('register_group_permission_panel'):
            _permission_panel_classes.append(fn())

    return _permission_panel_classes 
Example #11
Source File: utils.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_forms_for_user(user):
    """
    Return a queryset of form pages that this user is allowed to access the submissions for
    """
    editable_forms = UserPagePermissionsProxy(user).editable_pages()
    editable_forms = editable_forms.filter(content_type__in=get_form_types())

    # Apply hooks
    for fn in hooks.get_hooks('filter_form_submissions_for_user'):
        editable_forms = fn(user, editable_forms)

    return editable_forms 
Example #12
Source File: wagtailadmin_tags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def icons():
    icon_hooks = hooks.get_hooks('register_icons')
    icons = sorted(itertools.chain.from_iterable(hook([]) for hook in icon_hooks))
    return {'icons': icons} 
Example #13
Source File: users.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def edit(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    can_delete = user_can_delete_user(request.user, user)
    editing_self = request.user == user

    for fn in hooks.get_hooks('before_edit_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_edit_form()(request.POST, request.FILES, instance=user, editing_self=editing_self)
        if form.is_valid():
            user = form.save()

            if user == request.user and 'password1' in form.changed_data:
                # User is changing their own password; need to update their session hash
                update_session_auth_hash(request, user)

            messages.success(request, _("User '{0}' updated.").format(user), buttons=[
                messages.button(reverse('wagtailusers_users:edit', args=(user.pk,)), _('Edit'))
            ])
            for fn in hooks.get_hooks('after_edit_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be saved due to errors."))
    else:
        form = get_user_edit_form()(instance=user, editing_self=editing_self)

    return TemplateResponse(request, 'wagtailusers/users/edit.html', {
        'user': user,
        'form': form,
        'can_delete': can_delete,
    }) 
Example #14
Source File: feature_registry.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _scan_for_features(self):
        for fn in hooks.get_hooks('register_rich_text_features'):
            fn(self)
        self.has_scanned_for_features = True 
Example #15
Source File: views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve(request, path):
    # we need a valid Site object corresponding to this request in order to proceed
    site = Site.find_for_request(request)
    if not site:
        raise Http404

    path_components = [component for component in path.split('/') if component]
    page, args, kwargs = site.root_page.specific.route(request, path_components)

    for fn in hooks.get_hooks('before_serve_page'):
        result = fn(page, request, args, kwargs)
        if isinstance(result, HttpResponse):
            return result

    return page.serve(request, *args, **kwargs) 
Example #16
Source File: tests.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        # Create a group to edit
        self.test_group = Group.objects.create(name='test group')
        self.root_page = Page.objects.get(pk=1)
        self.root_add_permission = GroupPagePermission.objects.create(page=self.root_page,
                                                                      permission_type='add',
                                                                      group=self.test_group)
        self.home_page = Page.objects.get(pk=2)

        # Get the hook-registered permissions, and add one to this group
        self.registered_permissions = Permission.objects.none()
        for fn in hooks.get_hooks('register_permissions'):
            self.registered_permissions = self.registered_permissions | fn()
        self.existing_permission = self.registered_permissions.order_by('pk')[0]
        self.another_permission = self.registered_permissions.order_by('pk')[1]

        self.test_group.permissions.add(self.existing_permission)

        # set up collections to test document permissions
        self.root_collection = Collection.get_first_root_node()
        self.evil_plans_collection = self.root_collection.add_child(name="Evil plans")
        self.add_doc_permission = Permission.objects.get(
            content_type__app_label='wagtaildocs', codename='add_document'
        )
        self.change_doc_permission = Permission.objects.get(
            content_type__app_label='wagtaildocs', codename='change_document'
        )
        GroupCollectionPermission.objects.create(
            group=self.test_group,
            collection=self.evil_plans_collection,
            permission=self.add_doc_permission,
        )

        # Login
        self.login() 
Example #17
Source File: site_summary.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, request):
        self.request = request
        self.summary_items = []
        for fn in hooks.get_hooks('construct_homepage_summary_items'):
            fn(request, self.summary_items) 
Example #18
Source File: test_hooks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_before_hook(self):
        def before_hook():
            pass

        with self.register_hook('test_hook_name', before_hook, order=-1):
            hook_fns = hooks.get_hooks('test_hook_name')
            self.assertEqual(hook_fns, [before_hook, test_hook]) 
Example #19
Source File: search.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def registered_search_areas(self):
        return sorted([fn() for fn in hooks.get_hooks(self.register_hook_name)]) 
Example #20
Source File: test_hooks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_after_hook(self):
        def after_hook():
            pass

        with self.register_hook('test_hook_name', after_hook, order=1):
            hook_fns = hooks.get_hooks('test_hook_name')
            self.assertEqual(hook_fns, [test_hook, after_hook]) 
Example #21
Source File: chooser.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def search(request, parent_page_id=None):
    # A missing or empty page_type parameter indicates 'all page types' (i.e. descendants of wagtailcore.page)
    page_type_string = request.GET.get('page_type') or 'wagtailcore.page'

    try:
        desired_classes = page_models_from_string(page_type_string)
    except (ValueError, LookupError):
        raise Http404

    pages = Page.objects.all()
    # allow hooks to modify the queryset
    for hook in hooks.get_hooks('construct_page_chooser_queryset'):
        pages = hook(pages, request)

    search_form = SearchForm(request.GET)
    if search_form.is_valid() and search_form.cleaned_data['q']:
        pages = pages.exclude(
            depth=1  # never include root
        )
        pages = filter_page_type(pages, desired_classes)
        pages = pages.specific()
        pages = pages.search(search_form.cleaned_data['q'])
    else:
        pages = pages.none()

    paginator = Paginator(pages, per_page=25)
    pages = paginator.get_page(request.GET.get('p'))

    for page in pages:
        page.can_choose = True

    return TemplateResponse(
        request, 'wagtailadmin/chooser/_search_results.html',
        shared_context(request, {
            'searchform': search_form,
            'pages': pages,
            'page_type_string': page_type_string,
        })
    ) 
Example #22
Source File: menus.py    From wagtailmenus with MIT License 5 votes vote down vote up
def get_base_page_queryset(self):
        qs = Page.objects.filter(live=True, expired=False, show_in_menus=True)
        # allow hooks to modify the queryset
        for hook in hooks.get_hooks('menus_modify_base_page_queryset'):
            qs = hook(qs, **self.common_hook_kwargs)
        return qs 
Example #23
Source File: menus.py    From wagtailmenus with MIT License 5 votes vote down vote up
def get_base_menuitem_queryset(self):
        qs = self.get_menu_items_manager().for_display()

        # Prefetch minimal page values only. The rest will be
        # fetched by get_pages_for_display()
        qs = qs.select_related('link_page').defer(*[
            'link_page__{}'.format(f.name) for f in Page._meta.get_fields()
            if f.concrete and f.name not in ('id', 'path', 'depth')
        ])

        # allow hooks to modify the queryset
        for hook in hooks.get_hooks('menus_modify_base_menuitem_queryset'):
            qs = hook(qs, **self.common_hook_kwargs)
        return qs 
Example #24
Source File: __init__.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def populate(self):
        for fn in hooks.get_hooks('register_admin_viewset'):
            viewset = fn()
            self.register(viewset) 
Example #25
Source File: menu.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def registered_menu_items(self):
        if self._registered_menu_items is None:
            self._registered_menu_items = [fn() for fn in hooks.get_hooks(self.register_hook_name)]
        return self._registered_menu_items 
Example #26
Source File: menu.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_html(self, request):
        menu_items = self.menu_items_for_request(request)

        # provide a hook for modifying the menu, if construct_hook_name has been set
        if self.construct_hook_name:
            for fn in hooks.get_hooks(self.construct_hook_name):
                fn(request, menu_items)

        rendered_menu_items = []
        for item in sorted(menu_items, key=lambda i: i.order):
            rendered_menu_items.append(item.render_html(request))
        return mark_safe(''.join(rendered_menu_items)) 
Example #27
Source File: wagtailadmin_tags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page_listing_buttons(context, page, page_perms, is_parent=False):
    next_url = urlencode({"next": context.request.path})
    button_hooks = hooks.get_hooks('register_page_listing_buttons')
    buttons = sorted(itertools.chain.from_iterable(
        hook(page, page_perms, is_parent, next_url)
        for hook in button_hooks))

    for hook in hooks.get_hooks('construct_page_listing_buttons'):
        hook(buttons, page, page_perms, is_parent, context)

    return {'page': page, 'buttons': buttons} 
Example #28
Source File: collections.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_collection_contents(self):
        collection_contents = [
            hook(self.object)
            for hook in hooks.get_hooks('describe_collection_contents')
        ]

        # filter out any hook responses that report that the collection is empty
        # (by returning None, or a dict with 'count': 0)
        def is_nonempty(item_type):
            return item_type and item_type['count'] > 0

        return list(filter(is_nonempty, collection_contents)) 
Example #29
Source File: account.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def account(request):
    items = []

    for fn in hooks.get_hooks('register_account_menu_item'):
        item = fn(request)
        if item:
            items.append(item)

    return TemplateResponse(request, 'wagtailadmin/account/account.html', {
        'items': items,
    }) 
Example #30
Source File: pages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete(request, page_id):
    page = get_object_or_404(Page, id=page_id).specific
    if not page.permissions_for_user(request.user).can_delete():
        raise PermissionDenied

    with transaction.atomic():
        for fn in hooks.get_hooks('before_delete_page'):
            result = fn(request, page)
            if hasattr(result, 'status_code'):
                return result

        next_url = get_valid_next_url_from_request(request)

        if request.method == 'POST':
            parent_id = page.get_parent().id
            page.delete()

            messages.success(request, _("Page '{0}' deleted.").format(page.get_admin_display_title()))

            for fn in hooks.get_hooks('after_delete_page'):
                result = fn(request, page)
                if hasattr(result, 'status_code'):
                    return result

            if next_url:
                return redirect(next_url)
            return redirect('wagtailadmin_explore', parent_id)

    return TemplateResponse(request, 'wagtailadmin/pages/confirm_delete.html', {
        'page': page,
        'descendant_count': page.get_descendant_count(),
        'next': next_url,
    })