コード例 #1
0
ファイル: pages.py プロジェクト: jaydensmith/wagtail
def delete(request, page_id):
    page = get_object_or_404(Page, id=page_id)
    if not page.permissions_for_user(request.user).can_delete():
        raise PermissionDenied

    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.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 render(request, 'wagtailadmin/pages/confirm_delete.html', {
        'page': page,
        'descendant_count': page.get_descendant_count(),
        'next': next_url,
    })
コード例 #2
0
ファイル: pages.py プロジェクト: mvantellingen/wagtail
def delete(request, page_id):
    page = get_object_or_404(Page, id=page_id)
    if not page.permissions_for_user(request.user).can_delete():
        raise PermissionDenied

    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 render(
        request,
        "wagtailadmin/pages/confirm_delete.html",
        {"page": page, "descendant_count": page.get_descendant_count(), "next": next_url},
    )
コード例 #3
0
ファイル: utils.py プロジェクト: chrxr/wagtail
    def register_hook(self, hook_name, fn):
        from wagtail.wagtailcore import hooks

        hooks.register(hook_name, fn)
        try:
            yield
        finally:
            hooks.get_hooks(hook_name).remove(fn)
    def test_before_hook(self):
        def before_hook():
            pass

        with self.register_hook('test_hook_name', before_hook):
            hook_fns = hooks.get_hooks('test_hook_name')
            self.assertEqual(hook_fns, [test_hook, before_hook])
コード例 #5
0
ファイル: tests.py プロジェクト: jschneier/wagtail
    def setUp(self):
        # Create a group to edit
        self.test_group = Group.objects.create(name='test group')
        self.root_page = Page.objects.get(id=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(id=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()
    def test_after_hook(self):
        def after_hook():
            self

        with self.register_hook('test_hook_name', after_hook):
            hook_fns = hooks.get_hooks('test_hook_name')
            self.assertEqual(hook_fns, [test_hook, after_hook])
コード例 #7
0
ファイル: pages.py プロジェクト: Rakuli/wagtail
def delete(request, page_id):
    page = get_object_or_404(Page, id=page_id)
    if not page.permissions_for_user(request.user).can_delete():
        raise PermissionDenied

    if request.POST:
        if page.live:
            # fetch params to pass to the page_unpublished_signal, before the
            # deletion happens
            specific_class = page.specific_class
            specific_page = page.specific

        parent_id = page.get_parent().id
        page.delete()

        # If the page is live, send the unpublished signal
        if page.live:
            page_unpublished.send(sender=specific_class, instance=specific_page)

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

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

        return redirect('wagtailadmin_explore', parent_id)

    return render(request, 'wagtailadmin/pages/confirm_delete.html', {
        'page': page,
        'descendant_count': page.get_descendant_count()
    })
コード例 #8
0
ファイル: home.py プロジェクト: thenewguy/wagtail
def home(request):

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

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

    root_page = get_explorable_root_page(request.user)
    if root_page:
        root_site = root_page.get_site()
    else:
        root_site = None

    real_site_name = None
    if root_site:
        real_site_name = root_site.site_name if root_site.site_name else root_site.hostname

    return render(request, "wagtailadmin/home.html", {
        'root_page': root_page,
        'root_site': root_site,
        'site_name': real_site_name if real_site_name else settings.WAGTAIL_SITE_NAME,
        'panels': sorted(panels, key=lambda p: p.order),
        'user': request.user
    })
コード例 #9
0
ファイル: wagtailuserbar.py プロジェクト: DimiC/wagtail
def wagtailuserbar(context, position='bottom-right'):
    # Find request object
    try:
        request = context['request']
    except KeyError:
        return ''

    # Don't render if user doesn't have permission to access the admin area
    if not request.user.has_perm('wagtailadmin.access_admin'):
        return ''

    # Only render if the context contains a variable referencing a saved page
    page = get_page_instance(context)
    if page is None:
        return ''

    # Dont render anything if the page has not been saved - i.e. a preview
    if page.pk is None:
        return ''

    try:
        revision_id = request.revision_id
    except AttributeError:
        revision_id = None

    if revision_id is None:
        items = [
            AdminItem(),
            ExplorePageItem(Page.objects.get(id=page.id)),
            EditPageItem(Page.objects.get(id=page.id)),
            AddPageItem(Page.objects.get(id=page.id)),
        ]
    else:
        items = [
            AdminItem(),
            ExplorePageItem(PageRevision.objects.get(id=revision_id).page),
            EditPageItem(PageRevision.objects.get(id=revision_id).page),
            AddPageItem(PageRevision.objects.get(id=revision_id).page),
            ApproveModerationEditPageItem(PageRevision.objects.get(id=revision_id)),
            RejectModerationEditPageItem(PageRevision.objects.get(id=revision_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 userbar items
    return render_to_string('wagtailadmin/userbar/base.html', {
        'request': request,
        'items': rendered_items,
        'position': position,
        'page': page,
        'revision_id': revision_id
    })
コード例 #10
0
ファイル: groups.py プロジェクト: Anlim/wagtail
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
コード例 #11
0
ファイル: userbar.py プロジェクト: bjesus/wagtail
def run_deprecated_edit_bird_hook(request, items):
    for fn in hooks.get_hooks('construct_wagtail_edit_bird'):
        fn(request, items)

        warnings.warn(
            "The 'construct_wagtail_edit_bird' hook has been renamed to 'construct_wagtail_userbar'."
            "Please update function '%s' in '%s'." % (fn.__name__, fn.__module__), RemovedInWagtail12Warning
        )
コード例 #12
0
ファイル: test_admin.py プロジェクト: DimiC/wagtail
 def test_registered_permission(self):
     permission = Permission.objects.get_by_natural_key(
         app_label='tests', model='testsetting', codename='change_testsetting')
     for fn in hooks.get_hooks('register_permissions'):
         if permission in fn():
             break
     else:
         self.fail('Change permission for tests.TestSetting not registered')
コード例 #13
0
ファイル: rich_text.py プロジェクト: Eraldo/wagtail
    def clean(cls, html):
        if not cls.has_loaded_custom_whitelist_rules:
            for fn in hooks.get_hooks('construct_whitelister_element_rules'):
                cls.element_rules = cls.element_rules.copy()
                cls.element_rules.update(fn())
            cls.has_loaded_custom_whitelist_rules = True

        return super(DbWhitelister, cls).clean(html)
コード例 #14
0
ファイル: chooser.py プロジェクト: kapito/wagtail
def chooser(request):
    Document = get_document_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        DocumentForm = get_document_form(Document)
        uploadform = DocumentForm(user=request.user)
    else:
        uploadform = None

    documents = Document.objects.all()

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks('construct_document_chooser_queryset'):
        documents = hook(documents, request)

    q = None
    if 'q' in request.GET or 'p' in request.GET or 'collection_id' in request.GET:

        collection_id = request.GET.get('collection_id')
        if collection_id:
            documents = documents.filter(collection=collection_id)

        searchform = SearchForm(request.GET)
        if searchform.is_valid():
            q = searchform.cleaned_data['q']

            documents = documents.search(q)
            is_searching = True
        else:
            documents = documents.order_by('-created_at')
            is_searching = False

        # Pagination
        paginator, documents = paginate(request, documents, per_page=10)

        return render(request, "wagtaildocs/chooser/results.html", {
            'documents': documents,
            'query_string': q,
            'is_searching': is_searching,
        })
    else:
        searchform = SearchForm()

        collections = Collection.objects.all()
        if len(collections) < 2:
            collections = None

        documents = documents.order_by('-created_at')
        paginator, documents = paginate(request, documents, per_page=10)

        return render_modal_workflow(request, 'wagtaildocs/chooser/chooser.html', 'wagtaildocs/chooser/chooser.js', {
            'documents': documents,
            'uploadform': uploadform,
            'searchform': searchform,
            'collections': collections,
            'is_searching': False,
        })
コード例 #15
0
ファイル: collections.py プロジェクト: quru/wagtail
    def get_collection_contents(self):
        collection_contents = [hook(self.instance) 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))
コード例 #16
0
ファイル: models.py プロジェクト: tony/wagtail
    def _search_for_operations(cls):
        if cls._registered_operations is not None:
            return

        operations = []
        for fn in hooks.get_hooks('register_image_operations'):
            operations.extend(fn())

        cls._registered_operations = dict(operations)
コード例 #17
0
ファイル: models.py プロジェクト: signalkraft/wagtail
    def _search_for_operations(cls):
        if cls._registered_operations is not None:
            return

        operations = []
        for fn in hooks.get_hooks('register_image_operations'):
            operations.extend(fn())

        cls._registered_operations = dict(operations)
コード例 #18
0
def wagtailuserbar(context, position='bottom-right'):
    # Find request object
    request = context['request']


    # Don't render if user doesn't have permission to access the admin area
    if not request.user.has_perm('wagtailadmin.access_admin'):
        return ''

    # Only render if the context contains a variable referencing a saved page
    page = get_page_instance(context)
    if page is None:
        return ''

    # Dont render anything if the page has not been saved - i.e. a preview
    if page.pk is None:
        return ''

    try:
        revision_id = request.revision_id
    except AttributeError:
        revision_id = None

    if revision_id is None:
        items = [
            AdminItem(),
            ExplorePageItem(Page.objects.get(id=page.id)),
            EditPageItem(Page.objects.get(id=page.id)),
            AddPageItem(Page.objects.get(id=page.id)),
        ]
    else:
        items = [
            AdminItem(),
            ExplorePageItem(PageRevision.objects.get(id=revision_id).page),
            EditPageItem(PageRevision.objects.get(id=revision_id).page),
            AddPageItem(PageRevision.objects.get(id=revision_id).page),
            ApproveModerationEditPageItem(PageRevision.objects.get(id=revision_id)),
            RejectModerationEditPageItem(PageRevision.objects.get(id=revision_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 userbar items
    return render_to_string('wagtailadmin/userbar/base.html', {
        'request': request,
        'items': rendered_items,
        'position': position,
        'page': page,
        'revision_id': revision_id
    })
コード例 #19
0
ファイル: pages.py プロジェクト: tvenkat/wagtail
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', '-latest_revision_created_at')
    if ordering not in [
            'title', '-title', 'content_type', '-content_type', 'live',
            '-live', 'latest_revision_created_at',
            '-latest_revision_created_at', 'ord'
    ]:
        ordering = '-latest_revision_created_at'

    if ordering == 'ord':
        # preserve the native ordering from get_children()
        pass
    elif ordering == 'latest_revision_created_at':
        # order by oldest revision first.
        # Special case NULL entries - these should go at the top of the list.
        # Do this by annotating with Count('latest_revision_created_at'),
        # which returns 0 for these
        pages = pages.annotate(
            null_position=Count('latest_revision_created_at')).order_by(
                'null_position', 'latest_revision_created_at')
    elif ordering == '-latest_revision_created_at':
        # order by oldest revision first.
        # Special case NULL entries - these should go at the end of the list.
        pages = pages.annotate(
            null_position=Count('latest_revision_created_at')).order_by(
                '-null_position', '-latest_revision_created_at')
    else:
        pages = pages.order_by(ordering)

    # Don't paginate if sorting by page order - all pages must be shown to
    # allow drag-and-drop reordering
    do_paginate = ordering != 'ord'

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks('construct_explorer_page_queryset'):
        pages = hook(parent_page, pages, request)

    # Pagination
    if do_paginate:
        paginator, pages = paginate(request, pages, per_page=50)

    return render(
        request, 'wagtailadmin/pages/index.html', {
            'parent_page': parent_page,
            'ordering': ordering,
            'pagination_query_params': "ordering=%s" % ordering,
            'pages': pages,
            'do_paginate': do_paginate,
        })
コード例 #20
0
ファイル: wagtailadmin_tags.py プロジェクト: emg36/wagtail
def hook_output(hook_name):
    """
    Example: {% hook_output 'insert_editor_css' %}
    Whenever we have a hook whose functions take no parameters and return a string, this tag can be used
    to output the concatenation of all of those return values onto the page.
    Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content.
    """
    snippets = [fn() for fn in hooks.get_hooks(hook_name)]
    return mark_safe(''.join(snippets))
コード例 #21
0
ファイル: test_admin.py プロジェクト: jschneier/wagtail
 def test_registered_permission(self):
     permission = Permission.objects.get_by_natural_key(
         app_label="tests", model="testsetting", codename="change_testsetting"
     )
     for fn in hooks.get_hooks("register_permissions"):
         if permission in fn():
             break
     else:
         self.fail("Change permission for tests.TestSetting not registered")
コード例 #22
0
def hook_output(hook_name):
    """
    Example: {% hook_output 'insert_editor_css' %}
    Whenever we have a hook whose functions take no parameters and return a string, this tag can be used
    to output the concatenation of all of those return values onto the page.
    Note that the output is not escaped - it is the hook function's responsibility to escape unsafe content.
    """
    snippets = [fn() for fn in hooks.get_hooks(hook_name)]
    return "".join(snippets)
コード例 #23
0
 def registered_menu_items(self):
     if self._registered_menu_items is None:
         self._registered_menu_items = []
         for fn in hooks.get_hooks(self.register_hook_name):
             res = fn()
             if res and isinstance(res, MenuItem):
                 self._registered_menu_items.append(res)
             elif res and isinstance(res, list):
                 self._registered_menu_items += res
     return self._registered_menu_items
コード例 #24
0
ファイル: test_admin.py プロジェクト: wizardlie/wagtail
 def test_registered_permission(self):
     permission = Permission.objects.get_by_natural_key(
         app_label='tests',
         model='testsetting',
         codename='change_testsetting')
     for fn in hooks.get_hooks('register_permissions'):
         if permission in fn():
             break
     else:
         self.fail('Change permission for tests.TestSetting not registered')
コード例 #25
0
ファイル: wagtail_hooks.py プロジェクト: jbgury/aroe
def training_admin_view(request):
	panels = []
	for fn in hooks.get_hooks('construct_homepage_panels'):
		fn(request, panels)

	return render(request, "aroe/admin/trainings_management.html", {
		'site_name':settings.WAGTAIL_SITE_NAME,
		'panels': sorted(panels, key=lambda p:p.order),
		'user': request.user
		})
コード例 #26
0
ファイル: rich_text.py プロジェクト: Eraldo/wagtail
def get_link_handler(link_type):
    global LINK_HANDLERS, has_loaded_link_handlers

    if not has_loaded_link_handlers:
        for hook in hooks.get_hooks('register_rich_text_link_handler'):
            handler_name, handler = hook()
            LINK_HANDLERS[handler_name] = handler

        has_loaded_link_handlers = True

    return LINK_HANDLERS[link_type]
コード例 #27
0
ファイル: wagtailadmin_tags.py プロジェクト: Rakuli/wagtail
def main_nav(context):
    request = context['request']
    menu_items = [item for item in get_master_menu_item_list() if item.is_shown(request)]

    for fn in hooks.get_hooks('construct_main_menu'):
        fn(request, menu_items)

    return {
        'menu_items': sorted(menu_items, key=lambda i: i.order),
        'request': request,
    }
コード例 #28
0
def get_link_handler(link_type):
    global LINK_HANDLERS, has_loaded_link_handlers

    if not has_loaded_link_handlers:
        for hook in hooks.get_hooks('register_rich_text_link_handler'):
            handler_name, handler = hook()
            LINK_HANDLERS[handler_name] = handler

        has_loaded_link_handlers = True

    return LINK_HANDLERS[link_type]
コード例 #29
0
ファイル: views.py プロジェクト: fun-alex-alex2006hw/puput
    def get(self, request, *args, **kwargs):
        if not request.site:
            raise Http404
        path_components = list(operator.itemgetter(0, -1)(request.path.strip('/').split('/')))
        page, args, kwargs = request.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)
コード例 #30
0
def get_embed_handler(embed_type):
    global EMBED_HANDLERS, has_loaded_embed_handlers

    if not has_loaded_embed_handlers:
        for hook in hooks.get_hooks('register_rich_text_embed_handler'):
            handler_name, handler = hook()
            EMBED_HANDLERS[handler_name] = handler

        has_loaded_embed_handlers = True

    return EMBED_HANDLERS[embed_type]
コード例 #31
0
def get_master_menu_item_list():
    """
    Return the list of menu items registered with the 'register_admin_menu_item' hook.
    This is the "master list" because the final admin menu may vary per request
    according to the value of is_shown() and the construct_main_menu hook.
    """
    global _master_menu_item_list
    if _master_menu_item_list is None:
        _master_menu_item_list = [fn() for fn in hooks.get_hooks('register_admin_menu_item')]

    return _master_menu_item_list
コード例 #32
0
ファイル: rich_text.py プロジェクト: Eraldo/wagtail
def get_embed_handler(embed_type):
    global EMBED_HANDLERS, has_loaded_embed_handlers

    if not has_loaded_embed_handlers:
        for hook in hooks.get_hooks('register_rich_text_embed_handler'):
            handler_name, handler = hook()
            EMBED_HANDLERS[handler_name] = handler

        has_loaded_embed_handlers = True

    return EMBED_HANDLERS[embed_type]
コード例 #33
0
ファイル: models.py プロジェクト: thenewguy/wagtail
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
コード例 #34
0
ファイル: collections.py プロジェクト: Qnetis/university
    def get_collection_contents(self):
        collection_contents = [
            hook(self.instance)
            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))
コード例 #35
0
    def filter_queryset(self, request, queryset, view):
        if request.GET.get('for_explorer'):
            if not hasattr(queryset, '_filtered_by_child_of'):
                raise BadRequestError(
                    "filtering by for_explorer without child_of is not supported"
                )

            parent_page = queryset._filtered_by_child_of
            for hook in hooks.get_hooks('construct_explorer_page_queryset'):
                queryset = hook(parent_page, queryset, request)

        return queryset
コード例 #36
0
ファイル: models.py プロジェクト: uk-gov-mirror/nhsuk.wagtail
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
コード例 #37
0
    def get(self, request, *args, **kwargs):
        if not request.site:
            raise Http404
        path_components = list(
            operator.itemgetter(0, -1)(request.path.strip('/').split('/')))
        page, args, kwargs = request.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)
コード例 #38
0
def main_nav(context):
    request = context['request']
    menu_items = [
        item for item in get_master_menu_item_list() if item.is_shown(request)
    ]

    for fn in hooks.get_hooks('construct_main_menu'):
        fn(request, menu_items)

    return {
        'menu_items': sorted(menu_items, key=lambda i: i.order),
        'request': request,
    }
コード例 #39
0
def chooser(request):
    Report = get_report_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        ReportForm = get_report_form(Report)
        uploadform = ReportForm(user=request.user)
    else:
        uploadform = None

    reports = Report.objects.all()

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks('construct_report_chooser_queryset'):
        reports = hook(reports, request)

    q = None
    if 'q' in request.GET or 'p' in request.GET:

        searchform = SearchForm(request.GET)
        if searchform.is_valid():
            q = searchform.cleaned_data['q']

            reports = reports.search(q)
            is_searching = True
        else:
            reports = reports.order_by('-created_at')
            is_searching = False

        # Pagination
        paginator, reports = paginate(request, reports, per_page=10)

        return render(request, "wagtailreports/chooser/results.html", {
            'reports': reports,
            'query_string': q,
            'is_searching': is_searching,
        })
    else:
        searchform = SearchForm()

        reports = reports.order_by('-created_at')
        paginator, reports = paginate(request, reports, per_page=10)

        return render_modal_workflow(
            request, 'wagtailreports/chooser/chooser.html',
            'wagtailreports/chooser/chooser.js', {
                'reports': reports,
                'uploadform': uploadform,
                'searchform': searchform,
                'is_searching': False,
            })
コード例 #40
0
ファイル: userbar.py プロジェクト: Frankie-666/wagtail
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 render(request, "wagtailadmin/userbar/base.html", {"items": rendered_items})
コード例 #41
0
ファイル: utils.py プロジェクト: vixdigital/omni-forms
def run_permission_hooks(action, instance):
    """
    Simple method that runs permission hooks for the given instance
    Loops through all 'omniform_permission_check' hooks and calls each
    in turn passing:

     - action: The action being performed (create, update, delete, clone)
     - instance: The instance being operated on

    :param action: The action being performed
    :param instance: The model instance being worked on
    """
    for hook in hooks.get_hooks('omniform_permission_check'):
        hook(action, instance)
コード例 #42
0
ファイル: rich_text.py プロジェクト: caputomarcos/wagtailplus
    def clean(cls, html):
        """
        Returns cleaned HTML.

        :param html: the HTML to clean.
        :rtype: str.
        """
        if not cls.has_loaded_custom_whitelist_rules:
            for fn in hooks.get_hooks('construct_whitelister_element_rules'):
                cls.element_rules = cls.element_rules.copy()
                cls.element_rules.update(fn())
            cls.has_loaded_custom_whitelist_rules = True

        return super(FlexibleDbWhitelister, cls).clean(html)
コード例 #43
0
ファイル: rich_text.py プロジェクト: MariusCC/wagtailplus
    def clean(cls, html):
        """
        Returns cleaned HTML.

        :param html: the HTML to clean.
        :rtype: str.
        """
        if not cls.has_loaded_custom_whitelist_rules:
            for fn in hooks.get_hooks('construct_whitelister_element_rules'):
                cls.element_rules = cls.element_rules.copy()
                cls.element_rules.update(fn())
            cls.has_loaded_custom_whitelist_rules = True

        return super(FlexibleDbWhitelister, cls).clean(html)
コード例 #44
0
ファイル: views.py プロジェクト: C3-Desarrollo/puput
    def get(self, request, *args, **kwargs):
        if not request.site:
            raise Http404
        if request.resolver_match.url_name == 'entry_page_serve_slug':
            path_components = list(operator.itemgetter(0, -1)(request.path.strip('/').split('/')))
        else:
            path_components = [request.path.strip('/').split('/')[-1]]
        page, args, kwargs = request.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)
コード例 #45
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    if request.method == 'POST':
        image = Image(uploaded_by_user=request.user)
        form = ImageForm(request.POST,
                         request.FILES,
                         instance=image,
                         user=request.user)

        if form.is_valid():
            form.save()

            # Reindex the image to make sure all tags are indexed
            search_index.insert_or_update_object(image)

            if request.GET.get('select_format'):
                form = ImageInsertionForm(
                    initial={'alt_text': image.default_alt_text})
                return render_modal_workflow(
                    request, 'wagtailimages/chooser/select_format.html',
                    'wagtailimages/chooser/select_format.js', {
                        'image': image,
                        'form': form
                    })
            else:
                # not specifying a format; return the image details now
                return render_modal_workflow(
                    request, None, 'wagtailimages/chooser/image_chosen.js',
                    {'image_json': get_image_json(image)})
    else:
        form = ImageForm(user=request.user)

    images = Image.objects.order_by('-created_at')

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks('construct_image_chooser_queryset'):
        images = hook(images, request)

    paginator, images = paginate(request, images, per_page=12)

    context = get_chooser_context(request)
    context.update({
        'images': images,
        'uploadform': form,
    })
    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html',
                                 'wagtailimages/chooser/chooser.js', context)
コード例 #46
0
ファイル: wagtailadmin_tags.py プロジェクト: kingctan/wagtail
def main_nav(context):
    menu_items = [
        MenuItem(_('Explorer'), urlresolvers.reverse('wagtailadmin_explore_root'), classnames='icon icon-folder-open-inverse dl-trigger', order=100),
        MenuItem(_('Search'), urlresolvers.reverse('wagtailadmin_pages_search'), classnames='icon icon-search', order=200),
    ]

    request = context['request']

    for fn in hooks.get_hooks('construct_main_menu'):
        fn(request, menu_items)

    return {
        'menu_items': sorted(menu_items, key=lambda i: i.order),
        'request': request,
    }
コード例 #47
0
def main_nav(context):
    menu_items = [
        MenuItem(_('Explorer'), urlresolvers.reverse('wagtailadmin_explore_root'), classnames='icon icon-folder-open-inverse dl-trigger', order=100),
        MenuItem(_('Search'), urlresolvers.reverse('wagtailadmin_pages_search'), classnames='icon icon-search', order=200),
    ]

    request = context['request']

    for fn in hooks.get_hooks('construct_main_menu'):
        fn(request, menu_items)

    return {
        'menu_items': sorted(menu_items, key=lambda i: i.order),
        'request': request,
    }
コード例 #48
0
ファイル: views.py プロジェクト: emg36/wagtail
def serve(request, path):
    # we need a valid Site object corresponding to this request (set in wagtail.wagtailcore.middleware.SiteMiddleware)
    # in order to proceed
    if not request.site:
        raise Http404

    path_components = [component for component in path.split('/') if component]
    page, args, kwargs = request.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)
コード例 #49
0
ファイル: views.py プロジェクト: kapito/wagtail
def serve(request, path):
    # we need a valid Site object corresponding to this request (set in wagtail.wagtailcore.middleware.SiteMiddleware)
    # in order to proceed
    if not request.site:
        raise Http404

    path_components = [component for component in path.split('/') if component]
    page, args, kwargs = request.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)
コード例 #50
0
    def get(self, request, *args, **kwargs):
        if not request.site:
            raise Http404
        if request.resolver_match.url_name == 'entry_page_serve_slug':
            path_components = list(
                operator.itemgetter(0, -1)(request.path.strip('/').split('/')))
        else:
            path_components = [request.path.strip('/').split('/')[-1]]
        page, args, kwargs = request.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)
コード例 #51
0
ファイル: home.py プロジェクト: sixpearls/wagtail
def home(request):

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

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

    return render(request, "wagtailadmin/home.html", {
        'site_name': settings.WAGTAIL_SITE_NAME,
        'panels': sorted(panels, key=lambda p: p.order),
        'user': request.user
    })
コード例 #52
0
    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):
            try:
                rendered_menu_items.append(item.render_html(request))
            except TypeError:
                # fallback for older render_html methods that don't accept a request arg
                rendered_menu_items.append(item.render_html(request))

        return mark_safe(''.join(rendered_menu_items))
コード例 #53
0
ファイル: home.py プロジェクト: signalkraft/wagtail
def home(request):

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

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

    return render(
        request, "wagtailadmin/home.html", {
            'site_name': settings.WAGTAIL_SITE_NAME,
            'panels': sorted(panels, key=lambda p: p.order),
            'user': request.user
        })
コード例 #54
0
ファイル: tests.py プロジェクト: signalkraft/wagtail
    def setUp(self):
        # Create a group to edit
        self.test_group = Group.objects.create(name='test group')
        self.root_page = Page.objects.get(id=1)
        self.root_add_permission = GroupPagePermission.objects.create(
            page=self.root_page, permission_type='add', group=self.test_group)
        # 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)

        # Login
        self.login()
コード例 #55
0
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 render(request, 'wagtailadmin/userbar/base.html', {
        'items': rendered_items,
    })
コード例 #56
0
    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))
コード例 #57
0
ファイル: pages.py プロジェクト: rclark72/wagtail
def delete(request, page_id):
    page = get_object_or_404(Page, id=page_id)
    if not page.permissions_for_user(request.user).can_delete():
        raise PermissionDenied

    if request.POST:
        parent_id = page.get_parent().id
        page.delete()
        messages.success(request, _("Page '{0}' deleted.").format(page.title))

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

        return redirect('wagtailadmin_explore', parent_id)

    return render(request, 'wagtailadmin/pages/confirm_delete.html', {
        'page': page,
        'descendant_count': page.get_descendant_count()
    })
コード例 #58
0
def for_moderation(request, revision_id):
    items = [
        EditPageItem(PageRevision.objects.get(id=revision_id).page),
        AddPageItem(PageRevision.objects.get(id=revision_id).page),
        ApproveModerationEditPageItem(PageRevision.objects.get(id=revision_id)),
        RejectModerationEditPageItem(PageRevision.objects.get(id=revision_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 render(request, 'wagtailadmin/userbar/base.html', {
        'items': rendered_items,
    })
コード例 #59
0
def serve(request, path):
    # we need a valid Site object corresponding to this request (set in wagtail.wagtailcore.middleware.SiteMiddleware)
    # in order to proceed
    if not request.site:
        raise Http404

    path_components = [component for component in path.split('/') if component]
    route_result = request.site.root_page.specific.route(request, path_components)
    if isinstance(route_result, HttpResponse):
        warnings.warn(
            "Page.route should return an instance of wagtailcore.url_routing.RouteResult, not an HttpResponse",
            RemovedInWagtail06Warning
        )
        return route_result

    (page, args, kwargs) = route_result
    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)