Пример #1
0
def main_nav(context):
    menu_items = [
        MenuItem('Explorer', '#', 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']
    user = request.user

    if user.has_perm('wagtailimages.add_image'):
        menu_items.append(
            MenuItem('Images', urlresolvers.reverse('wagtailimages_index'), classnames='icon icon-image', order=300)
        )
    if user.has_perm('wagtaildocs.add_document'):
        menu_items.append(
            MenuItem('Documents', urlresolvers.reverse('wagtaildocs_index'), classnames='icon icon-doc-full-inverse', order=400)
        )

    if user_can_edit_snippets(user):
        menu_items.append(
            MenuItem('Snippets', urlresolvers.reverse('wagtailsnippets_index'), classnames='icon icon-snippet', order=500)
        )

    if user.has_module_perms('auth'):
        menu_items.append(
            MenuItem('Users', urlresolvers.reverse('wagtailusers_index'), classnames='icon icon-user', order=600)
        )

    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,
    }
Пример #2
0
    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 = dict(
                    cls.element_rules.items() + fn().items())
            cls.has_loaded_custom_whitelist_rules = True

        return super(DbWhitelister, cls).clean(html)
Пример #3
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 u''.join(snippets)
Пример #4
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 u"".join(snippets)
Пример #5
0
def main_nav(context):
    menu_items = [
        MenuItem(_("Explorer"), "#", 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}
Пример #6
0
def main_nav(context):
    menu_items = [
        MenuItem('Explorer',
                 '#',
                 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']
    user = request.user

    if user.has_perm('wagtailimages.add_image'):
        menu_items.append(
            MenuItem('Images',
                     urlresolvers.reverse('wagtailimages_index'),
                     classnames='icon icon-image',
                     order=300))
    if user.has_perm('wagtaildocs.add_document'):
        menu_items.append(
            MenuItem('Documents',
                     urlresolvers.reverse('wagtaildocs_index'),
                     classnames='icon icon-doc-full-inverse',
                     order=400))

    if user_can_edit_snippets(user):
        menu_items.append(
            MenuItem('Snippets',
                     urlresolvers.reverse('wagtailsnippets_index'),
                     classnames='icon icon-snippet',
                     order=500))

    if user.has_module_perms('auth'):
        menu_items.append(
            MenuItem('Users',
                     urlresolvers.reverse('wagtailusers_index'),
                     classnames='icon icon-user',
                     order=600))

    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,
    }
Пример #7
0
def main_nav(context):
    menu_items = [
        MenuItem(_('Explorer'), '#', 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,
    }
Пример #8
0
def main_nav(context):
    menu_items = [
        MenuItem(_('Explorer'), '#', 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,
    }
Пример #9
0
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
    })
Пример #10
0
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
    })
Пример #11
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_edit_bird'):
        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,
    })
Пример #12
0
def main_nav(context):
    menu_items = [
        MenuItem(_("Explorer"), "#", 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"]
    user = request.user

    if user.has_perm("wagtailimages.add_image"):
        menu_items.append(
            MenuItem(_("Images"), urlresolvers.reverse("wagtailimages_index"), classnames="icon icon-image", order=300)
        )
    if user.has_perm("wagtaildocs.add_document"):
        menu_items.append(
            MenuItem(
                _("Documents"),
                urlresolvers.reverse("wagtaildocs_index"),
                classnames="icon icon-doc-full-inverse",
                order=400,
            )
        )

    if user_can_edit_snippets(user):
        menu_items.append(
            MenuItem(
                _("Snippets"), urlresolvers.reverse("wagtailsnippets_index"), classnames="icon icon-snippet", order=500
            )
        )

    if user.has_module_perms("auth"):
        menu_items.append(
            MenuItem(_("Users"), urlresolvers.reverse("wagtailusers_index"), classnames="icon icon-user", order=600)
        )

    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}
Пример #13
0
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()
    })
Пример #14
0
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()
    })
Пример #15
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_edit_bird'):
        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,
    })
Пример #16
0
    url(r'^choose-page/(\d+)/$',
        chooser.browse,
        name='wagtailadmin_choose_page_child'),
    url(r'^choose-external-link/$',
        chooser.external_link,
        name='wagtailadmin_choose_page_external_link'),
    url(r'^choose-email-link/$',
        chooser.email_link,
        name='wagtailadmin_choose_page_email_link'),
    url(r'^tag-autocomplete/$',
        tags.autocomplete,
        name='wagtailadmin_tag_autocomplete'),
    url(r'^account/$', account.account, name='wagtailadmin_account'),
    url(r'^account/change_password/$',
        account.change_password,
        name='wagtailadmin_account_change_password'),
    url(r'^logout/$', account.logout, name='wagtailadmin_logout'),
    url(r'^userbar/(\d+)/$',
        userbar.for_frontend,
        name='wagtailadmin_userbar_frontend'),
    url(r'^userbar/moderation/(\d+)/$',
        userbar.for_moderation,
        name='wagtailadmin_userbar_moderation'),
]

# Import additional urlpatterns from any apps that define a register_admin_urls hook
for fn in hooks.get_hooks('register_admin_urls'):
    urls = fn()
    if urls:
        urlpatterns += urls
Пример #17
0
    url(r'^pages/(\d+)/move/$', pages.move_choose_destination, name='wagtailadmin_pages_move'),
    url(r'^pages/(\d+)/move/(\d+)/$', pages.move_choose_destination, name='wagtailadmin_pages_move_choose_destination'),
    url(r'^pages/(\d+)/move/(\d+)/confirm/$', pages.move_confirm, name='wagtailadmin_pages_move_confirm'),
    url(r'^pages/(\d+)/set_position/$', pages.set_page_position, name='wagtailadmin_pages_set_page_position'),

    url(r'^pages/moderation/(\d+)/approve/$', pages.approve_moderation, name='wagtailadmin_pages_approve_moderation'),
    url(r'^pages/moderation/(\d+)/reject/$', pages.reject_moderation, name='wagtailadmin_pages_reject_moderation'),
    url(r'^pages/moderation/(\d+)/preview/$', pages.preview_for_moderation, name='wagtailadmin_pages_preview_for_moderation'),

    url(r'^choose-page/$', chooser.browse, name='wagtailadmin_choose_page'),
    url(r'^choose-page/(\d+)/$', chooser.browse, name='wagtailadmin_choose_page_child'),
    url(r'^choose-external-link/$', chooser.external_link, name='wagtailadmin_choose_page_external_link'),
    url(r'^choose-email-link/$', chooser.email_link, name='wagtailadmin_choose_page_email_link'),

    url(r'^tag-autocomplete/$', tags.autocomplete, name='wagtailadmin_tag_autocomplete'),

    url(r'^account/$', account.account, name='wagtailadmin_account'),
    url(r'^account/change_password/$', account.change_password, name='wagtailadmin_account_change_password'),
    url(r'^logout/$', account.logout, name='wagtailadmin_logout'),

    url(r'^userbar/(\d+)/$', userbar.for_frontend, name='wagtailadmin_userbar_frontend'),
    url(r'^userbar/moderation/(\d+)/$', userbar.for_moderation, name='wagtailadmin_userbar_moderation'),
]


# Import additional urlpatterns from any apps that define a register_admin_urls hook
for fn in hooks.get_hooks('register_admin_urls'):
    urls = fn()
    if urls:
        urlpatterns += urls
Пример #18
0
def edit(request, page_id):
    latest_revision = get_object_or_404(Page, id=page_id).get_latest_revision()
    page = get_object_or_404(Page, id=page_id).get_latest_revision_as_page()
    parent = page.get_parent()

    page_perms = page.permissions_for_user(request.user)
    if not page_perms.can_edit():
        raise PermissionDenied

    edit_handler_class = get_page_edit_handler(page.__class__)
    form_class = edit_handler_class.get_form_class(page.__class__)

    errors_debug = None

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        # Stick an extra validator into the form to make sure that the slug is not already in use
        def clean_slug(slug):
            # Make sure the slug isn't already in use
            if parent.get_children().filter(slug=slug).exclude(id=page_id).count() > 0:
                raise ValidationError(_("This slug is already in use"))
            return slug
        form.fields['slug'].clean = clean_slug

        # Stick another validator into the form to check that the scheduled publishing settings are set correctly
        def clean():
            cleaned_data = form_class.clean(form)

            # Go live must be before expire
            go_live_at = cleaned_data.get('go_live_at')
            expire_at = cleaned_data.get('expire_at')

            if go_live_at and expire_at:
                if go_live_at > expire_at:
                    msg = _('Go live date/time must be before expiry date/time')
                    form._errors['go_live_at'] = form.error_class([msg])
                    form._errors['expire_at'] = form.error_class([msg])
                    del cleaned_data['go_live_at']
                    del cleaned_data['expire_at']

            # Expire must be in the future
            expire_at = cleaned_data.get('expire_at')

            if expire_at and expire_at < timezone.now():
                form._errors['expire_at'] = form.error_class([_('Expiry date/time must be in the future')])
                del cleaned_data['expire_at']

            return cleaned_data
        form.clean = clean

        if form.is_valid():
            is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))
            go_live_at = form.cleaned_data.get('go_live_at')
            future_go_live = go_live_at and go_live_at > timezone.now()
            approved_go_live_at = None

            if is_publishing:
                page.has_unpublished_changes = False
                page.expired = False
                if future_go_live:
                    page.live = False
                    # Set approved_go_live_at only if publishing
                    approved_go_live_at = go_live_at
                else:
                    page.live = True
                form.save()
                # Clear approved_go_live_at for older revisions
                page.revisions.update(
                    submitted_for_moderation=False,
                    approved_go_live_at=None,
                )
            else:
                # not publishing the page
                if page.live:
                    # To avoid overwriting the live version, we only save the page
                    # to the revisions table
                    form.save(commit=False)
                    Page.objects.filter(id=page.id).update(has_unpublished_changes=True)
                else:
                    page.has_unpublished_changes = True
                    form.save()

            page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
                approved_go_live_at=approved_go_live_at
            )

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, 'submitted', request.user.id)
            else:
                messages.success(request, _("Page '{0}' updated.").format(page.title))

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

            return redirect('wagtailadmin_explore', page.get_parent().id)
        else:
            messages.error(request, _("The page could not be saved due to validation errors"))

            edit_handler = edit_handler_class(instance=page, form=form)
            errors_debug = (
                repr(edit_handler.form.errors)
                + repr([(name, formset.errors) for (name, formset) in edit_handler.form.formsets.iteritems() if formset.errors])
            )
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        messages.warning(request, _("This page is currently awaiting moderation"))

    return render(request, 'wagtailadmin/pages/edit.html', {
        'page': page,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
        'display_modes': page.get_page_modes(),
        'form': form, # Used in unit tests
    })
Пример #19
0
def edit(request, page_id):
    latest_revision = get_object_or_404(Page, id=page_id).get_latest_revision()
    page = get_object_or_404(Page, id=page_id).get_latest_revision_as_page()
    parent = page.get_parent()

    page_perms = page.permissions_for_user(request.user)
    if not page_perms.can_edit():
        raise PermissionDenied

    edit_handler_class = get_page_edit_handler(page.__class__)
    form_class = edit_handler_class.get_form_class(page.__class__)

    errors_debug = None

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        # Stick an extra validator into the form to make sure that the slug is not already in use
        def clean_slug(slug):
            # Make sure the slug isn't already in use
            if parent.get_children().filter(slug=slug).exclude(id=page_id).count() > 0:
                raise ValidationError(_("This slug is already in use"))
            return slug
        form.fields['slug'].clean = clean_slug

        if form.is_valid():
            is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))

            if is_publishing:
                page.live = True
                page.has_unpublished_changes = False
                form.save()
                page.revisions.update(submitted_for_moderation=False)
            else:
                # not publishing the page
                if page.live:
                    # To avoid overwriting the live version, we only save the page
                    # to the revisions table
                    form.save(commit=False)
                    Page.objects.filter(id=page.id).update(has_unpublished_changes=True)
                else:
                    page.has_unpublished_changes = True
                    form.save()

            page.save_revision(user=request.user, submitted_for_moderation=is_submitting)

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, 'submitted', request.user.id)
            else:
                messages.success(request, _("Page '{0}' updated.").format(page.title))

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

            return redirect('wagtailadmin_explore', page.get_parent().id)
        else:
            messages.error(request, _("The page could not be saved due to validation errors"))
            edit_handler = edit_handler_class(instance=page, form=form)
            errors_debug = (
                repr(edit_handler.form.errors)
                + repr([(name, formset.errors) for (name, formset) in edit_handler.form.formsets.iteritems() if formset.errors])
            )
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        messages.warning(request, _("This page is currently awaiting moderation"))

    return render(request, 'wagtailadmin/pages/edit.html', {
        'page': page,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
    })
Пример #20
0
def create(request, content_type_app_name, content_type_model_name, parent_page_id):
    parent_page = get_object_or_404(Page, id=parent_page_id).specific
    parent_page_perms = parent_page.permissions_for_user(request.user)
    if not parent_page_perms.can_add_subpage():
        raise PermissionDenied

    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    page_class = content_type.model_class()

    # page must be in the list of allowed subpage types for this parent ID
    # == Restriction temporarily relaxed so that as superusers we can add index pages and things -
    # == TODO: reinstate this for regular editors when we have distinct user types
    #
    # if page_class not in parent_page.clean_subpage_types():
    #     messages.error(request, "Sorry, you do not have access to create a page of type '%s' here." % content_type.name)
    #     return redirect('wagtailadmin_pages_select_type')

    page = page_class(owner=request.user)
    edit_handler_class = get_page_edit_handler(page_class)
    form_class = edit_handler_class.get_form_class(page_class)

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        # Stick an extra validator into the form to make sure that the slug is not already in use
        def clean_slug(slug):
            # Make sure the slug isn't already in use
            if parent_page.get_children().filter(slug=slug).count() > 0:
                raise ValidationError(_("This slug is already in use"))
            return slug
        form.fields['slug'].clean = clean_slug

        if form.is_valid():
            page = form.save(commit=False)  # don't save yet, as we need treebeard to assign tree params

            is_publishing = bool(request.POST.get('action-publish')) and parent_page_perms.can_publish_subpage()
            is_submitting = bool(request.POST.get('action-submit'))

            if is_publishing:
                page.live = True
                page.has_unpublished_changes = False
            else:
                page.live = False
                page.has_unpublished_changes = True

            parent_page.add_child(page)  # assign tree parameters - will cause page to be saved
            page.save_revision(user=request.user, submitted_for_moderation=is_submitting)

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, 'submitted', request.user.id)
            else:
                messages.success(request, _("Page '{0}' created.").format(page.title))

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

            return redirect('wagtailadmin_explore', page.get_parent().id)
        else:
            messages.error(request, _("The page could not be created due to errors."))
            edit_handler = edit_handler_class(instance=page, form=form)
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    return render(request, 'wagtailadmin/pages/create.html', {
        'content_type': content_type,
        'page_class': page_class,
        'parent_page': parent_page,
        'edit_handler': edit_handler,
    })
Пример #21
0
def edit(request, page_id):
    latest_revision = get_object_or_404(Page, id=page_id).get_latest_revision()
    page = get_object_or_404(Page, id=page_id).get_latest_revision_as_page()
    page_perms = page.permissions_for_user(request.user)
    if not page_perms.can_edit():
        raise PermissionDenied

    edit_handler_class = get_page_edit_handler(page.__class__)
    form_class = edit_handler_class.get_form_class(page.__class__)

    errors_debug = None

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        if form.is_valid():
            is_publishing = bool(request.POST.get("action-publish")) and page_perms.can_publish()
            is_submitting = bool(request.POST.get("action-submit"))

            if is_publishing:
                page.live = True
                page.has_unpublished_changes = False
                form.save()
                page.revisions.update(submitted_for_moderation=False)
            else:
                # not publishing the page
                if page.live:
                    # To avoid overwriting the live version, we only save the page
                    # to the revisions table
                    form.save(commit=False)
                    Page.objects.filter(id=page.id).update(has_unpublished_changes=True)
                else:
                    page.has_unpublished_changes = True
                    form.save()

            page.save_revision(user=request.user, submitted_for_moderation=is_submitting)

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, "submitted", request.user.id)
            else:
                messages.success(request, _("Page '{0}' updated.").format(page.title))

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

            return redirect("wagtailadmin_explore", page.get_parent().id)
        else:
            messages.error(request, _("The page could not be saved due to validation errors"))
            edit_handler = edit_handler_class(instance=page, form=form)
            errors_debug = repr(edit_handler.form.errors) + repr(
                [(name, formset.errors) for (name, formset) in edit_handler.form.formsets.iteritems() if formset.errors]
            )
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        messages.warning(request, _("This page is currently awaiting moderation"))

    return render(
        request,
        "wagtailadmin/pages/edit.html",
        {"page": page, "edit_handler": edit_handler, "errors_debug": errors_debug},
    )
Пример #22
0
def create(request, content_type_app_name, content_type_model_name, parent_page_id):
    parent_page = get_object_or_404(Page, id=parent_page_id).specific
    parent_page_perms = parent_page.permissions_for_user(request.user)
    if not parent_page_perms.can_add_subpage():
        raise PermissionDenied

    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    # Get class
    page_class = content_type.model_class()

    # Make sure the class is a descendant of Page
    if not issubclass(page_class, Page):
        raise Http404

    # page must be in the list of allowed subpage types for this parent ID
    if content_type not in parent_page.clean_subpage_types():
        raise PermissionDenied

    page = page_class(owner=request.user)
    edit_handler_class = get_page_edit_handler(page_class)
    form_class = edit_handler_class.get_form_class(page_class)

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        # Stick an extra validator into the form to make sure that the slug is not already in use
        def clean_slug(slug):
            # Make sure the slug isn't already in use
            if parent_page.get_children().filter(slug=slug).count() > 0:
                raise ValidationError(_("This slug is already in use"))
            return slug
        form.fields['slug'].clean = clean_slug

        # Stick another validator into the form to check that the scheduled publishing settings are set correctly
        def clean():
            cleaned_data = form_class.clean(form)

            # Go live must be before expire
            go_live_at = cleaned_data.get('go_live_at')
            expire_at = cleaned_data.get('expire_at')

            if go_live_at and expire_at:
                if go_live_at > expire_at:
                    msg = _('Go live date/time must be before expiry date/time')
                    form._errors['go_live_at'] = form.error_class([msg])
                    form._errors['expire_at'] = form.error_class([msg])
                    del cleaned_data['go_live_at']
                    del cleaned_data['expire_at']

            # Expire must be in the future
            expire_at = cleaned_data.get('expire_at')

            if expire_at and expire_at < timezone.now():
                form._errors['expire_at'] = form.error_class([_('Expiry date/time must be in the future')])
                del cleaned_data['expire_at']

            return cleaned_data
        form.clean = clean

        if form.is_valid():
            page = form.save(commit=False)  # don't save yet, as we need treebeard to assign tree params

            is_publishing = bool(request.POST.get('action-publish')) and parent_page_perms.can_publish_subpage()
            is_submitting = bool(request.POST.get('action-submit'))
            go_live_at = form.cleaned_data.get('go_live_at')
            future_go_live = go_live_at and go_live_at > timezone.now()
            approved_go_live_at = None

            if is_publishing:
                page.has_unpublished_changes = False
                page.expired = False
                if future_go_live:
                    page.live = False
                    # Set approved_go_live_at only if is publishing
                    # and the future_go_live is actually in future
                    approved_go_live_at = go_live_at
                else:
                    page.live = True
            else:
                page.live = False
                page.has_unpublished_changes = True

            parent_page.add_child(instance=page)  # assign tree parameters - will cause page to be saved

            # Pass approved_go_live_at to save_revision
            page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
                approved_go_live_at=approved_go_live_at
            )

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, 'submitted', request.user.id)
            else:
                messages.success(request, _("Page '{0}' created.").format(page.title))

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

            return redirect('wagtailadmin_explore', page.get_parent().id)
        else:
            messages.error(request, _("The page could not be created due to validation errors"))
            edit_handler = edit_handler_class(instance=page, form=form)
    else:
        signals.init_new_page.send(sender=create, page=page, parent=parent_page)
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    return render(request, 'wagtailadmin/pages/create.html', {
        'content_type': content_type,
        'page_class': page_class,
        'parent_page': parent_page,
        'edit_handler': edit_handler,
        'display_modes': page.get_page_modes(),
        'form': form, # Used in unit tests
    })
Пример #23
0
def edit(request, page_id):
    latest_revision = get_object_or_404(Page, id=page_id).get_latest_revision()
    page = get_object_or_404(Page, id=page_id).get_latest_revision_as_page()
    page_perms = page.permissions_for_user(request.user)
    if not page_perms.can_edit():
        raise PermissionDenied

    edit_handler_class = get_page_edit_handler(page.__class__)
    form_class = edit_handler_class.get_form_class(page.__class__)

    errors_debug = None

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        if form.is_valid():
            is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))

            if is_publishing:
                page.live = True
                page.has_unpublished_changes = False
                form.save()
                page.revisions.update(submitted_for_moderation=False)
            else:
                # not publishing the page
                if page.live:
                    # To avoid overwriting the live version, we only save the page
                    # to the revisions table
                    form.save(commit=False)
                    Page.objects.filter(id=page.id).update(has_unpublished_changes=True)
                else:
                    page.has_unpublished_changes = True
                    form.save()

            page.save_revision(user=request.user, submitted_for_moderation=is_submitting)

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, 'submitted', request.user.id)
            else:
                messages.success(request, _("Page '{0}' updated.").format(page.title))

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

            return redirect('wagtailadmin_explore', page.get_parent().id)
        else:
            messages.error(request, _("The page could not be saved due to validation errors"))
            edit_handler = edit_handler_class(instance=page, form=form)
            errors_debug = (
                repr(edit_handler.form.errors)
                + repr([(name, formset.errors) for (name, formset) in edit_handler.form.formsets.iteritems() if formset.errors])
            )
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        messages.warning(request, _("This page is currently awaiting moderation"))

    return render(request, 'wagtailadmin/pages/edit.html', {
        'page': page,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
    })
Пример #24
0
def create(request, content_type_app_name, content_type_model_name, parent_page_id):
    parent_page = get_object_or_404(Page, id=parent_page_id).specific
    parent_page_perms = parent_page.permissions_for_user(request.user)
    if not parent_page_perms.can_add_subpage():
        raise PermissionDenied

    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    page_class = content_type.model_class()

    # page must be in the list of allowed subpage types for this parent ID
    # == Restriction temporarily relaxed so that as superusers we can add index pages and things -
    # == TODO: reinstate this for regular editors when we have distinct user types
    #
    # if page_class not in parent_page.clean_subpage_types():
    #     messages.error(request, "Sorry, you do not have access to create a page of type '%s' here." % content_type.name)
    #     return redirect('wagtailadmin_pages_select_type')

    page = page_class(owner=request.user)
    edit_handler_class = get_page_edit_handler(page_class)
    form_class = edit_handler_class.get_form_class(page_class)

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=page)

        # Stick an extra validator into the form to make sure that the slug is not already in use
        def clean_slug(slug):
            # Make sure the slug isn't already in use
            if parent_page.get_children().filter(slug=slug).count() > 0:
                raise ValidationError(_("This slug is already in use"))
            return slug
        form.fields['slug'].clean = clean_slug

        if form.is_valid():
            page = form.save(commit=False)  # don't save yet, as we need treebeard to assign tree params

            is_publishing = bool(request.POST.get('action-publish')) and parent_page_perms.can_publish_subpage()
            is_submitting = bool(request.POST.get('action-submit'))

            if is_publishing:
                page.live = True
                page.has_unpublished_changes = False
            else:
                page.live = False
                page.has_unpublished_changes = True

            parent_page.add_child(page)  # assign tree parameters - will cause page to be saved
            page.save_revision(user=request.user, submitted_for_moderation=is_submitting)

            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title))
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title))
                tasks.send_notification.delay(page.get_latest_revision().id, 'submitted', request.user.id)
            else:
                messages.success(request, _("Page '{0}' created.").format(page.title))

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

            return redirect('wagtailadmin_explore', page.get_parent().id)
        else:
            messages.error(request, _("The page could not be created due to errors."))
            edit_handler = edit_handler_class(instance=page, form=form)
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)

    return render(request, 'wagtailadmin/pages/create.html', {
        'content_type': content_type,
        'page_class': page_class,
        'parent_page': parent_page,
        'edit_handler': edit_handler,
    })