def test_request_hook_true(self): # A POST should never be cached. response = self.client.post(reverse("cached_view")) self.assertEqual(response.get(self.header_name, None), Status.SKIP.value) response = self.client.post(reverse("cached_view")) self.assertEqual(response.get(self.header_name, None), Status.SKIP.value) # Register hook and assert it was actually registered. hooks.register("is_request_cacheable", hook_true) hook_fns = hooks.get_hooks("is_request_cacheable") self.assertEqual(hook_fns, [hook_true]) # Setting `is_request_cacheale=True` does not really do much, because # the response still has the final say in whether or not the response is # cached. The no-cache page will still not be cached due to the # response. However a simple POST request will now be checked against # the cache, although once again, it will probably not get cached due to # the response. response = self.client.post(reverse("cached_view")) self.assertEqual(response.get(self.header_name, None), Status.MISS.value) response = self.client.post(reverse("cached_view")) self.assertEqual(response.get(self.header_name, None), Status.MISS.value)
def test_response_hook_any(self): # Register hook and assert it was actually registered. hooks.register("is_response_cacheable", hook_any) hook_fns = hooks.get_hooks("is_response_cacheable") self.assertEqual(hook_fns, [hook_any]) # The page should be cached normally due to hook returning garbage. self.test_page_hit()
def test_response_hook_false(self): # Register hook and assert it was actually registered. hooks.register("is_response_cacheable", hook_false) hook_fns = hooks.get_hooks("is_response_cacheable") self.assertEqual(hook_fns, [hook_false]) # The cached page should be force skipped due to the hook returning false. self.get_skip(self.page_cachedpage.get_url()) self.get_skip(self.page_cachedpage.get_url())
def register_hook(self, hook_name, fn, order=0): from wagtail.core import hooks hooks.register(hook_name, fn, order) try: yield finally: hooks._hooks[hook_name].remove((fn, order))
def test_response_hook_true(self): # Register hook and assert it was actually registered. hooks.register("is_response_cacheable", hook_true) hook_fns = hooks.get_hooks("is_response_cacheable") self.assertEqual(hook_fns, [hook_true]) # The no-cache page should be force cached due to the hook returning true. self.get_miss(self.page_cachecontrolpage.get_url()) self.get_hit(self.page_cachecontrolpage.get_url())
class CollectionAdminURLFinder(ModelAdminURLFinder): permission_policy = collection_permission_policy edit_url_name = "wagtailadmin_collections:edit" register_admin_url_finder(Collection, CollectionAdminURLFinder) class WorkflowAdminURLFinder(ModelAdminURLFinder): permission_policy = workflow_permission_policy edit_url_name = "wagtailadmin_workflows:edit" register_admin_url_finder(Workflow, WorkflowAdminURLFinder) class WorkflowTaskAdminURLFinder(ModelAdminURLFinder): permission_policy = task_permission_policy edit_url_name = "wagtailadmin_workflows:edit_task" register_admin_url_finder(Task, WorkflowTaskAdminURLFinder) for action_class in [ DeleteBulkAction, MoveBulkAction, PublishBulkAction, UnpublishBulkAction, ]: hooks.register("register_bulk_action", action_class)
'hallo', 'edit-html', HalloPlugin( name='editHtmlButton', js=['js/html_editor.js'], ) ) def editor_css(): return format_html( '<link rel="stylesheet" href="' + settings.STATIC_URL + 'css/question-tips.css">\n') hooks.register('insert_editor_css', editor_css) @hooks.register('register_admin_menu_item') def register_export_menu_item(): return MenuItem( 'Export Ask data', reverse('export-ask'), classnames='icon icon-download', order=99999, ) @hooks.register('register_admin_urls') def register_export_url(): return [url('export-ask', export_data, name='export-ask')]
def setUpClass(cls): hooks.register('test_hook_name', test_hook)
from django.utils.html import format_html from pkg_resources import parse_version try: from django.templatetags.static import static except ImportError: # fallback for Django <2.1 from django.contrib.staticfiles.templatetags.staticfiles import static try: from wagtail import __version__ as WAGTAIL_VERSION from wagtail.core import hooks except ImportError: # fallback for Wagtail <2.0 from wagtail.wagtailcore import hooks from wagtail.wagtailcore import __version__ as WAGTAIL_VERSION def import_wagtailfontawesome_stylesheet(): return format_html('<link rel="stylesheet" href="{}">', static('wagtailfontawesome/css/wagtailfontawesome.css')) # New Wagtail versions support importing CSS throughout the admin. # Fall back to the old hook (editor screen only) for older versions. if parse_version(WAGTAIL_VERSION) >= parse_version('1.4'): admin_stylesheet_hook = 'insert_global_admin_css' else: admin_stylesheet_hook = 'insert_editor_css' hooks.register(admin_stylesheet_hook, import_wagtailfontawesome_stylesheet)
from django.utils.html import format_html from pkg_resources import parse_version try: from django.templatetags.static import static except ImportError: # Fallback for Django <2.1 from django.contrib.staticfiles.templatetags.staticfiles import static try: from wagtail import __version__ as WAGTAIL_VERSION from wagtail.core import hooks except ImportError: # Fallback for Wagtal <2.0 from wagtail.wagtailcore import __version__ as WAGTAIL_VERSION from wagtail.wagtailcore import hooks def extraicons_stylesheet(): return format_html('<link rel="stylesheet" href="{}">', static('wagtailextraicons/css/main.css')) # New Wagtail versions support importing CSS throughout the admin. # Fall back to the old hook (editor screen only) for older versions. if parse_version(WAGTAIL_VERSION) >= parse_version('1.4'): admin_stylesheet_hook = 'insert_global_admin_css' else: admin_stylesheet_hook = 'insert_editor_css' hooks.register(admin_stylesheet_hook, extraicons_stylesheet)
return { 'div': attribute_rule({'class': True}), 'p': attribute_rule({'class': True}), 'a': attribute_rule({'target': True, 'href': check_url, 'id': True, 'class': True}), 'span': attribute_rule({'class': True, 'id': True}), 'i': attribute_rule({'class': True}), 'img': attribute_rule({'class': True}), 'iframe': attribute_rule({'id': True, 'class': True, 'src': True, 'style': True, 'frameborder': True, 'allowfullscreen': True, 'width': True, 'height': True}), } hooks.register('construct_whitelister_element_rules', whitelister_element_rules) def editor_css(): """Doc string.""" return format_html(""" <link href="{0}{1}" rel="stylesheet" type="text/x-scss"> """, settings.STATIC_URL, 'vendor/font-awesome/scss/font-awesome.scss') hooks.register('insert_editor_css', editor_css)
from .forms import FavouriteColourForm # Register one hook using decorators... @hooks.register("insert_editor_css") def editor_css(): return """<link rel="stylesheet" href="/path/to/my/custom.css">""" # And the other using old-style function calls def editor_js(): return """<script src="/path/to/my/custom.js"></script>""" hooks.register("insert_editor_js", editor_js) 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>") hooks.register("before_serve_page", block_googlebot) class KittensMenuItem(MenuItem): def is_shown(self, request): return not request.GET.get("hide-kittens", False)
def collapsible_js(): return format_html( '<script src="{}?v={}"></script>', static('coderedcms/js/codered-editor.js'), __version__, ) def clear_wagtailcache(*args, **kwargs): clear_cache() # Clear cache whenever pages/snippets are changed. Err on the side of clearing # the cache vs not clearing the cache, as this usually leads to support requests # when staff members make edits but do not see the changes. hooks.register('after_delete_page', clear_wagtailcache) hooks.register('after_move_page', clear_wagtailcache) hooks.register('after_publish_page', clear_wagtailcache) hooks.register('after_unpublish_page', clear_wagtailcache) hooks.register('after_create_snippet', clear_wagtailcache) hooks.register('after_edit_snippet', clear_wagtailcache) hooks.register('after_delete_snippet', clear_wagtailcache) @hooks.register('filter_form_submissions_for_user') def codered_forms(user, editable_forms): from coderedcms.models import CoderedFormMixin """ Add our own CoderedFormPage to editable_forms, since wagtail is unaware of its existence. Essentially this is a fork of wagtail.contrib.forms.get_forms_for_user() and wagtail.contrib.forms.get_form_types()
instance=restriction, initial={'return_url': request.get_full_path()}) action_url = reverse('wagtaildocs_authenticate_with_password', args=[restriction.id]) password_required_template = getattr( settings, 'DOCUMENT_PASSWORD_REQUIRED_TEMPLATE', 'wagtaildocs/password_required.html') context = {'form': form, 'action_url': action_url} return TemplateResponse(request, password_required_template, context) elif restriction.restriction_type in [ BaseViewRestriction.LOGIN, BaseViewRestriction.GROUPS ]: return require_wagtail_login(next=request.get_full_path()) class DocumentAdminURLFinder(ModelAdminURLFinder): edit_url_name = 'wagtaildocs:edit' permission_policy = permission_policy register_admin_url_finder(get_document_model(), DocumentAdminURLFinder) for action_class in [ AddTagsBulkAction, AddToCollectionBulkAction, DeleteBulkAction ]: hooks.register('register_bulk_action', action_class)
from django.http import HttpResponse from wagtail.core import hooks @hooks.register('before_serve_document', order=-1) def serve_document(document, request): subscribed = False if 'NV-Subscribed' in request.COOKIES: subscribed = request.COOKIES['NV-Subscribed'] if not subscribed: return HttpResponse("<h2>NerdVenture.net<h2><p>You must be subscribed to download!</P>") hooks.register('before_serve_document', serve_document)
review.send_request_emails() # clear original confirmation message as set by the create/edit view, # so that we can replace it with our own list(django_messages.get_messages(request)) message = _("Page '{0}' has been submitted for review.").format( page.get_admin_display_title()) messages.success(request, message) # redirect back to the explorer return redirect('wagtailadmin_explore', page.get_parent().id) hooks.register('after_create_page', handle_submit_for_review) hooks.register('after_edit_page', handle_submit_for_review) class ReviewsMenuItem(MenuItem): def is_shown(self, request): return bool(Review.get_pages_with_reviews_for_user(request.user)) @hooks.register('register_admin_menu_item') def register_images_menu_item(): return ReviewsMenuItem(_('Reviews'), reverse('wagtail_review_admin:dashboard'), name='reviews', classnames='icon icon-tick', order=1000)
def setUpClass(cls): hooks.register("test_hook_name", test_hook)
from wagtail.admin.widgets import Button from wagtail.core import hooks # Register one hook using decorators... @hooks.register('insert_editor_css') def editor_css(): return """<link rel="stylesheet" href="/path/to/my/custom.css">""" # And the other using old-style function calls def editor_js(): return """<script src="/path/to/my/custom.js"></script>""" hooks.register('insert_editor_js', editor_js) 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>") hooks.register('before_serve_page', block_googlebot) class KittensMenuItem(MenuItem): @property def media(self): return forms.Media(js=[static('testapp/js/kittens.js')])
def inner(fn): hooks.register('register_page_listing_buttons', fn) return fn
js_files = ["js/vendor/hallo-code.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('halloheadings'); registerHalloPlugin('hallocode'); </script> """) hooks.register("insert_editor_js", editor_js) def editor_css(): return format_html('<link rel="stylesheet" href="' + settings.STATIC_URL + 'css/vendor/font-awesome.min.css">') hooks.register("insert_editor_css", editor_css) @hooks.register("construct_whitelister_element_rules") def whitelister_element_rules(): return { "blockquote": allow_without_attributes, "pre": allow_without_attributes,
from wagtail.admin.search import SearchArea from wagtail.core import hooks # Register one hook using decorators... @hooks.register('insert_editor_css') def editor_css(): return """<link rel="stylesheet" href="/path/to/my/custom.css">""" # And the other using old-style function calls def editor_js(): return """<script src="/path/to/my/custom.js"></script>""" hooks.register('insert_editor_js', editor_js) 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>") hooks.register('before_serve_page', block_googlebot) class KittensMenuItem(MenuItem): @property def media(self): return forms.Media(js=[static('testapp/js/kittens.js')])
from wagtail.core.whitelist import attribute_rule, check_url def whitelister_element_rules(): return { 'p': attribute_rule({'class': True}), 'a': attribute_rule({'href': check_url, 'id': True, 'class': True}), 'span': attribute_rule({'class': True}), 'i': attribute_rule({'class': True}), 'iframe': attribute_rule( {'id': True, 'class': True, 'src': True, 'style': True, 'frameborder': True, 'allowfullscreen': True, 'width': True, 'height': True}), } hooks.register('construct_whitelister_element_rules', whitelister_element_rules) def editor_css(): return format_html(""" <link href="{0}{1}" rel="stylesheet" type="text/x-scss"> """, settings.STATIC_URL, 'vendor/font-awesome/scss/font-awesome.scss') hooks.register('insert_editor_css', editor_css) def editor_js(): js_files = [
from wagtail.admin.search import SearchArea from wagtail.core import hooks from wagtail.core.whitelist import allow_without_attributes, attribute_rule, check_url # Register one hook using decorators... @hooks.register('insert_editor_css') def editor_css(): return """<link rel="stylesheet" href="/path/to/my/custom.css">""" def editor_js(): return """<script src="/path/to/my/custom.js"></script>""" hooks.register('insert_editor_js', editor_js) # And the other using old-style function calls def whitelister_element_rules(): return { 'blockquote': allow_without_attributes, 'a': attribute_rule({'href': check_url, 'target': True}), } hooks.register('construct_whitelister_element_rules', whitelister_element_rules) def block_googlebot(page, request, serve_args, serve_kwargs):