HooksΒΆ
On loading, Wagtail will search for any app with the file wagtail_hooks.py and execute the contents. This provides a way to register your own functions to execute at certain points in Wagtail’s execution, such as when a Page object is saved or when the main menu is constructed.
Registering functions with a Wagtail hook is done through the @hooks.register decorator:
from wagtail.wagtailcore import hooks
@hooks.register('name_of_hook')
def my_hook_function(arg1, arg2...)
# your code here
Alternatively, hooks.register can be called as an ordinary function, passing in the name of the hook and a handler function defined elsewhere:
hooks.register('name_of_hook', my_hook_function)
The available hooks are:
before_serve_page
Called when Wagtail is about to serve a page. The callable passed into the hook will receive the page object, the request object, and the
argsandkwargsthat will be passed to the page’sserve()method. If the callable returns anHttpResponse, that response will be returned immediately to the user, and Wagtail will not proceed to callserve()on the page.from wagtail.wagtailcore import hooks @hooks.register('before_serve_page') def block_googlebot(page, request, serve_args, serve_kwargs): if request.META.get('HTTP_USER_AGENT') == 'GoogleBot': return HttpResponse("<h1>bad googlebot no cookie</h1>")
Changed in version 1.0: The hook was renamed from construct_wagtail_edit_bird
construct_wagtail_userbarAdd or remove items from the wagtail userbar. Add, edit, and moderation tools are provided by default. The callable passed into the hook must take the
requestobject and a list of menu objects,items. The menu item objects must have arendermethod which can take arequestobject and return the HTML string representing the menu item. See the userbar templates and menu item classes for more information.from wagtail.wagtailcore import hooks class UserbarPuppyLinkItem(object): def render(self, request): return '<li><a href="http://cuteoverload.com/tag/puppehs/" ' \ + 'target="_parent" class="action icon icon-wagtail">Puppies!</a></li>' @hooks.register('construct_wagtail_userbar') def add_puppy_link_item(request, items): return items.append( UserbarPuppyLinkItem() )
construct_homepage_panelsAdd or remove panels from the Wagtail admin homepage. The callable passed into this hook should take a
requestobject and a list ofpanels, objects which have arender()method returning a string. The objects also have anorderproperty, an integer used for ordering the panels. The default panels use integers between100and300.from django.utils.safestring import mark_safe from wagtail.wagtailcore import hooks class WelcomePanel(object): order = 50 def render(self): return mark_safe(""" <section class="panel summary nice-padding"> <h3>No, but seriously -- welcome to the admin homepage.</h3> </section> """) @hooks.register('construct_homepage_panels') def add_another_welcome_panel(request, panels): return panels.append( WelcomePanel() )
construct_homepage_summary_itemsNew in version 1.0.
Add or remove items from the ‘site summary’ bar on the admin homepage (which shows the number of pages and other object that exist on the site). The callable passed into this hook should take a
requestobject and a list ofSummaryItemobjects to be modified as required. These objects have arender()method, which returns an HTML string, and anorderproperty, which is an integer that specifies the order in which the items will appear.
after_create_pageDo something with a
Pageobject after it has been saved to the database (as a published page or a revision). The callable passed to this hook should take arequestobject and apageobject. The function does not have to return anything, but if an object with astatus_codeproperty is returned, Wagtail will use it as a response object. By default, Wagtail will instead redirect to the Explorer page for the new page’s parent.from django.http import HttpResponse from wagtail.wagtailcore import hooks @hooks.register('after_create_page') def do_after_page_create(request, page): return HttpResponse("Congrats on making content!", content_type="text/plain")
after_edit_page- Do something with a
Pageobject after it has been updated. Uses the same behavior asafter_create_page.
after_delete_page- Do something after a
Pageobject is deleted. Uses the same behavior asafter_create_page.
register_admin_urlsRegister additional admin page URLs. The callable fed into this hook should return a list of Django URL patterns which define the structure of the pages and endpoints of your extension to the Wagtail admin. For more about vanilla Django URLconfs and views, see url dispatcher.
from django.http import HttpResponse from django.conf.urls import url from wagtail.wagtailcore import hooks def admin_view( request ): return HttpResponse( \ "I have approximate knowledge of many things!", \ content_type="text/plain") @hooks.register('register_admin_urls') def urlconf_time(): return [ url(r'^how_did_you_almost_know_my_name/$', admin_view, name='frank' ), ]
Add an item to the Wagtail admin menu. The callable passed to this hook must return an instance of
wagtail.wagtailadmin.menu.MenuItem. New items can be constructed from theMenuItemclass by passing in alabelwhich will be the text in the menu item, and the URL of the admin page you want the menu item to link to (usually by callingreverse()on the admin view you’ve set up). Additionally, the following keyword arguments are accepted:
name: an internal name used to identify the menu item; defaults to the slugified form of the label. Also applied as a CSS class to the wrapping <li>, as"menu-{name}".classnames: additional classnames applied to the link, used to give it an icon attrs: additional HTML attributes to apply to the link order: an integer which determines the item’s position in the menu
MenuItemcan be subclassed to customise the HTML output, specify Javascript files required by the menu item, or conditionally show or hide the item for specific requests (for example, to apply permission checks); see the source code (wagtail/wagtailadmin/menu.py) for details.from django.core.urlresolvers import reverse from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem @hooks.register('register_admin_menu_item') def register_frank_menu_item(): return MenuItem('Frank', reverse('frank'), classnames='icon icon-folder-inverse', order=10000)
insert_editor_jsAdd additional Javascript files or code snippets to the page editor. Output must be compatible with
compress, as local static includes or string.from django.utils.html import format_html, format_html_join from django.conf import settings from wagtail.wagtailcore import hooks @hooks.register('insert_editor_js') def editor_js(): js_files = [ 'demo/js/hallo-plugins/hallo-demo-plugin.js', ] js_includes = format_html_join('\n', '<script src="{0}{1}"></script>', ((settings.STATIC_URL, filename) for filename in js_files) ) return js_includes + format_html( """ <script> registerHalloPlugin('demoeditor'); </script> """ )
insert_editor_cssAdd additional CSS or SCSS files or snippets to the page editor. Output must be compatible with
compress, as local static includes or string.from django.utils.html import format_html from django.conf import settings from wagtail.wagtailcore import hooks @hooks.register('insert_editor_css') def editor_css(): return format_html('<link rel="stylesheet" href="' \ + settings.STATIC_URL \ + 'demo/css/vendor/font-awesome/css/font-awesome.min.css">')
construct_whitelister_element_rules
Customise the rules that define which HTML elements are allowed in rich text areas. By default only a limited set of HTML elements and attributes are whitelisted - all others are stripped out. The callables passed into this hook must return a dict, which maps element names to handler functions that will perform some kind of manipulation of the element. These handler functions receive the element as a BeautifulSoup Tag object.
The
wagtail.wagtailcore.whitelistmodule provides a few helper functions to assist in defining these handlers:allow_without_attributes, a handler which preserves the element but strips out all of its attributes, andattribute_rulewhich accepts a dict specifying how to handle each attribute, and returns a handler function. This dict will map attribute names to either True (indicating that the attribute should be kept), False (indicating that it should be dropped), or a callable (which takes the initial attribute value and returns either a final value for the attribute, or None to drop the attribute).For example, the following hook function will add the
<blockquote>element to the whitelist, and allow thetargetattribute on<a>elements:from wagtail.wagtailcore import hooks from wagtail.wagtailcore.whitelist import attribute_rule, check_url, allow_without_attributes @hooks.register('construct_whitelister_element_rules') def whitelister_element_rules(): return { 'blockquote': allow_without_attributes, 'a': attribute_rule({'href': check_url, 'target': True}), }
register_permissionsNew in version 0.7.
Return a queryset of Permission objects to be shown in the Groups administration area.