Exemplo n.º 1
0
def reject_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(
            request,
            _("The page '{0}' is not currently awaiting moderation.").format(
                revision.page.title))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.reject_moderation()
        messages.success(request,
                         _("Page '{0}' rejected for publication.").format(
                             revision.page.title),
                         buttons=[
                             messages.button(
                                 reverse('wagtailadmin_pages:edit',
                                         args=(revision.page.id, )), _('Edit'))
                         ])
        send_notification(revision.id, 'rejected', request.user.id)

    return redirect('wagtailadmin_home')
Exemplo n.º 2
0
def reject_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(request, _("The page '{0}' is not currently awaiting moderation.").format(revision.page.title))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.reject_moderation()
        messages.success(request, _("Page '{0}' rejected for publication.").format(revision.page.title))
        send_notification(revision.id, 'rejected', request.user.id)

    return redirect('wagtailadmin_home')
Exemplo n.º 3
0
def approve_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(
            request,
            _("The page '{0}' is not currently awaiting moderation.").format(revision.page.get_admin_display_title()),
        )
        return redirect("wagtailadmin_home")

    if request.method == "POST":
        revision.approve_moderation()
        messages.success(
            request,
            _("Page '{0}' published.").format(revision.page.get_admin_display_title()),
            buttons=[
                messages.button(revision.page.url, _("View live")),
                messages.button(reverse("wagtailadmin_pages:edit", args=(revision.page.id,)), _("Edit")),
            ],
        )
        if not send_notification(revision.id, "approved", request.user.pk):
            messages.error(request, _("Failed to send approval notifications"))

    return redirect("wagtailadmin_home")
Exemplo n.º 4
0
def approve_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(
            request,
            _("The page '{0}' is not currently awaiting moderation.").format(
                revision.page.get_admin_display_title()))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.approve_moderation()
        messages.success(request,
                         _("Page '{0}' published.").format(
                             revision.page.get_admin_display_title()),
                         buttons=[
                             messages.button(revision.page.url,
                                             _('View live'),
                                             new_window=True),
                             messages.button(
                                 reverse('wagtailadmin_pages:edit',
                                         args=(revision.page.id, )), _('Edit'))
                         ])
        if not send_notification(revision.id, 'approved', request.user.pk):
            messages.error(request, _("Failed to send approval notifications"))

    return redirect('wagtailadmin_home')
Exemplo n.º 5
0
def approve_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(request, _("The page '{0}' is not currently awaiting moderation.").format(revision.page.title))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.approve_moderation()
        messages.success(request, _("Page '{0}' published.").format(revision.page.title), buttons=[
            messages.button(revision.page.url, _('View live')),
            messages.button(reverse('wagtailadmin_pages:edit', args=(revision.page.id,)), _('Edit'))
        ])
        send_notification(revision.id, 'approved', request.user.id)

    return redirect('wagtailadmin_home')
Exemplo n.º 6
0
def approve_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(
            request,
            _("The page '{0}' is not currently awaiting moderation.").format(
                revision.page.title))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.approve_moderation()
        messages.success(
            request,
            _("Page '{0}' published.").format(revision.page.title))
        send_notification(revision.id, 'approved', request.user.id)

    return redirect('wagtailadmin_home')
Exemplo n.º 7
0
def submit_blog(request, blog_index):

    form = BlogForm(data=request.POST or None, label_suffix='')

    if request.method == 'POST' and form.is_valid():
        blog_page = form.save(commit=False)
        blog_page.slug = slugify(blog_page.title)
        blog = blog_index.add_child(instance=blog_page)

        if blog:
            blog.unpublish()

            for tag in request.POST.getlist('tags'):
                BlogPageTag.objects.create(tag=Tag.objects.get(id=tag),
                                           content_object=blog)
            if request.POST.get('tags_additional'):
                for tag_name in request.POST.get('tags_additional').split(","):
                    tag_name = tag_name.lstrip().rstrip()
                    tag, created = Tag.objects.get_or_create(name=tag_name)
                    BlogPageTag.objects.create(
                        tag=tag,
                        content_object=blog
                    )

            # Submit page for moderation. This requires first saving a revision.
            blog.save_revision(submitted_for_moderation=True)
            # Then send the notification. Last param None means do not exclude any
            # moderators from email (internally wagtail would exclude the user
            # submitting from such emails, be we are submitting something from an
            # anonymous user, so no one should be excluded from the email).
            send_notification(blog.get_latest_revision().id, 'submitted', None)
        return HttpResponseRedirect(blog_index.url + blog_index.reverse_subpage('thanks'))

    tags = Tag.objects.filter(
                portal_pages_blogpagetag_items__isnull=False).order_by('name').distinct('name')
    context = {
        'form': form,
        'tags': tags,
        'blog_index': blog_index,
    }
    return render(request, 'portal_pages/blog_page_add.html', context)
Exemplo n.º 8
0
def submit_blog(request, blog_index):

    form = BlogForm(data=request.POST or None, label_suffix='')

    if request.method == 'POST' and form.is_valid():
        blog_page = form.save(commit=False)
        blog_page.slug = slugify(blog_page.title)
        blog = blog_index.add_child(instance=blog_page)

        if blog:
            blog.unpublish()

            for tag in request.POST.getlist('tags'):
                BlogPageTag.objects.create(tag=Tag.objects.get(id=tag),
                                           content_object=blog)
            if request.POST.get('tags_additional'):
                for tag_name in request.POST.get('tags_additional').split(","):
                    tag_name = tag_name.lstrip().rstrip()
                    tag, created = Tag.objects.get_or_create(name=tag_name)
                    BlogPageTag.objects.create(tag=tag, content_object=blog)

            # Submit page for moderation. This requires first saving a revision.
            blog.save_revision(submitted_for_moderation=True)
            # Then send the notification. Last param None means do not exclude any
            # moderators from email (internally wagtail would exclude the user
            # submitting from such emails, be we are submitting something from an
            # anonymous user, so no one should be excluded from the email).
            send_notification(blog.get_latest_revision().id, 'submitted', None)
        return HttpResponseRedirect(blog_index.url +
                                    blog_index.reverse_subpage('thanks'))

    tags = Tag.objects.filter(portal_pages_blogpagetag_items__isnull=False
                              ).order_by('name').distinct('name')
    context = {
        'form': form,
        'tags': tags,
        'blog_index': blog_index,
    }
    return render(request, 'portal_pages/blog_page_add.html', context)
Exemplo n.º 9
0
def reject_moderation(request, revision_id):
    revision = get_object_or_404(PageRevision, id=revision_id)
    if not revision.page.permissions_for_user(request.user).can_publish():
        raise PermissionDenied

    if not revision.submitted_for_moderation:
        messages.error(request, _("The page '{0}' is not currently awaiting moderation.").format(revision.page.get_admin_display_title()))
        return redirect('wagtailadmin_home')

    if request.method == 'POST':
        revision.reject_moderation()
        messages.success(request, _("Page '{0}' rejected for publication.").format(revision.page.get_admin_display_title()), buttons=[
            messages.button(reverse('wagtailadmin_pages:edit', args=(revision.page.id,)), _('Edit'))
        ])
        if not send_notification(revision.id, 'rejected', request.user.pk):
            messages.error(request, _("Failed to send rejection notifications"))

    return redirect('wagtailadmin_home')
Exemplo n.º 10
0
def submit_case_study(request, case_study_index):

    form = CaseStudyForm(data=request.POST or None, label_suffix='')

    # If the user uploaded a flow document we want the flow_json_file_form to validate it is a
    # valid document, but if no file was uploaded then proceed with an
    # unbound FlowJSONFileForm. This avoids re-display due to errors in the main form
    # erroneously telling the user that the flow file is required (it is required
    # for that form, but the entire form is optional).
    if request.FILES:
        flow_json_file_form = FlowJSONFileForm(data=request.POST,
                                               files=request.FILES,
                                               label_suffix='')
        flow_json_file_form_valid = flow_json_file_form.is_valid()
    else:
        flow_json_file_form = FlowJSONFileForm(label_suffix='')
        flow_json_file_form_valid = True

    if request.method == 'POST' and form.is_valid(
    ) and flow_json_file_form_valid:
        case_study_page = form.save(commit=False)
        if request.POST.get('year_start') and request.POST.get('month_start'):
            full_date = request.POST.get(
                'year_start') + '-' + request.POST.get('month_start') + '-01'
            case_study_page.date = datetime.strptime(full_date,
                                                     '%Y-%m-%d').date()
        case_study_page.slug = slugify(case_study_page.title)
        case_study = case_study_index.add_child(instance=case_study_page)

        if case_study:
            case_study.unpublish()
            if request.FILES:
                downloadable_package = flow_json_file_form.save(commit=False)
                downloadable_package.title = "Document for %s" % case_study_page.title
                downloadable_package.save()
                case_study.downloadable_package = downloadable_package

            for focus_area in request.POST.getlist('focus_areas'):
                FocusAreaCaseStudy.objects.create(
                    focusarea=FocusArea.objects.get(id=focus_area),
                    page=case_study)
            if request.POST.get('focus_areas_additional'):
                for focus_area_name in request.POST.get(
                        'focus_areas_additional').split(","):
                    focus_area_name = focus_area_name.lstrip().rstrip(
                    ).capitalize()
                    focus_area, created = FocusArea.objects.get_or_create(
                        name=focus_area_name)
                    FocusAreaCaseStudy.objects.create(focusarea=focus_area,
                                                      page=case_study)
            for organization in request.POST.getlist('organizations'):
                OrganizationCaseStudy.objects.create(
                    organization=Organization.objects.get(id=organization),
                    page=case_study)
            if request.POST.get('organizations_additional'):
                for organization_name in request.POST.get(
                        'organizations_additional').split(","):
                    organization_name = organization_name.lstrip().rstrip(
                    ).capitalize()
                    organization, created = Organization.objects.get_or_create(
                        name=organization_name)
                    OrganizationCaseStudy.objects.create(
                        organization=organization, page=case_study)
            for region in request.POST.getlist('regions'):
                RegionCaseStudy.objects.create(
                    region=Region.objects.get(id=region), page=case_study)
            for country in request.POST.getlist('countries'):
                CountryCaseStudy.objects.create(
                    country=Country.objects.get(id=country), page=case_study)

            # Submit page for moderation. This requires first saving a revision.
            case_study.save_revision(submitted_for_moderation=True)
            # Then send the notification. Last param None means do not exclude any
            # moderators from email (internally wagtail would exclude the user
            # submitting from such emails, be we are submitting something from an
            # anonymous user, so no one should be excluded from the email).
            send_notification(case_study.get_latest_revision().id, 'submitted',
                              None)
        return HttpResponseRedirect(case_study_index.url +
                                    case_study_index.reverse_subpage('thanks'))

    focus_areas = FocusArea.objects.order_by('name')
    organizations = Organization.objects.order_by('name')
    countries = Country.objects.order_by('name')
    regions = Region.objects.order_by('name')
    base_year = datetime.today().year
    years = [base_year - x for x in range(0, 100)]
    months = [
        'January', 'February', 'March', 'April', 'May', 'June', 'July',
        'August', 'September', 'October', 'November', 'December'
    ]
    months = [('%02d' % x, y) for x, y in list(enumerate(months, 1))
              ]  # months = [('01', 'Jan'), ('02', 'Feb')], ...
    marketplace_index = MarketplaceIndexPage.objects.live()[0]
    context = {
        'form': form,
        'flow_json_file_form': flow_json_file_form,
        'focus_areas': focus_areas,
        'organizations': organizations,
        'years': years,
        'months': months,
        'countries': countries,
        'regions': regions,
        'case_study_index': case_study_index,
        'marketplace_index': marketplace_index,
    }
    return render(request, 'portal_pages/case_study_page_add.html', context)
Exemplo n.º 11
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.allowed_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)
        validate_page_form(form, parent_page)

        if form.is_valid():
            page = form.save(commit=False)

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

            if not is_publishing:
                page.live = False

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                messages.success(request, _("Page '{0}' created and published.").format(page.title), buttons=[
                    messages.button(page.url, _('View live')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                ])
            elif is_submitting:
                messages.success(request, _("Page '{0}' created and submitted for moderation.").format(page.title), buttons=[
                    messages.button(reverse('wagtailadmin_pages:view_draft', args=(page.id,)), _('View draft')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                ])
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages:edit', page.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,
        'preview_modes': page.preview_modes,
        'form': form, # Used in unit tests
    })
Exemplo n.º 12
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.allowed_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)
        validate_page_form(form, parent_page)

        if form.is_valid():
            page = form.save(commit=False)

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

            if not is_publishing:
                page.live = False

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                messages.success(request,
                                 _("Page '{0}' created and published.").format(
                                     page.title),
                                 buttons=[
                                     messages.button(page.url, _('View live')),
                                     messages.button(
                                         reverse('wagtailadmin_pages:edit',
                                                 args=(page.id, )), _('Edit'))
                                 ])
            elif is_submitting:
                messages.success(
                    request,
                    _("Page '{0}' created and submitted for moderation."
                      ).format(page.title),
                    buttons=[
                        messages.button(
                            reverse('wagtailadmin_pages:view_draft',
                                    args=(page.id, )), _('View draft')),
                        messages.button(
                            reverse('wagtailadmin_pages:edit',
                                    args=(page.id, )), _('Edit'))
                    ])
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages:edit', page.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,
            'preview_modes': page.preview_modes,
            'form': form,  # Used in unit tests
        })
Exemplo n.º 13
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()

    content_type = ContentType.objects.get_for_model(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)
        validate_page_form(form, parent, page)

        if form.is_valid() and not page.locked:
            page = form.save(commit=False)

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

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                messages.success(request,
                                 _("Page '{0}' published.").format(page.title),
                                 buttons=[
                                     messages.button(page.url, _('View live')),
                                     messages.button(
                                         reverse('wagtailadmin_pages:edit',
                                                 args=(page_id, )), _('Edit'))
                                 ])
            elif is_submitting:
                messages.success(
                    request,
                    _("Page '{0}' submitted for moderation.").format(
                        page.title),
                    buttons=[
                        messages.button(
                            reverse('wagtailadmin_pages:view_draft',
                                    args=(page_id, )), _('View draft')),
                        messages.button(
                            reverse('wagtailadmin_pages:edit',
                                    args=(page_id, )), _('Edit'))
                    ])
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages:edit', page.id)
        else:
            if page.locked:
                messages.error(
                    request, _("The page could not be saved as it is locked"))
            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.items()
                 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,
            'content_type': content_type,
            'edit_handler': edit_handler,
            'errors_debug': errors_debug,
            'preview_modes': page.preview_modes,
            'form': form,  # Used in unit tests
        })
Exemplo n.º 14
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()

    content_type = ContentType.objects.get_for_model(page)
    page_class = content_type.model_class()

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

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

    edit_handler_class = page_class.get_edit_handler()
    form_class = edit_handler_class.get_form_class(page_class)

    next_url = get_valid_next_url_from_request(request)

    errors_debug = None

    if request.method == 'POST':
        form = form_class(request.POST,
                          request.FILES,
                          instance=page,
                          parent_page=parent)

        if form.is_valid() and not page.locked:
            page = form.save(commit=False)

            is_publishing = bool(request.POST.get(
                'action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))
            is_reverting = bool(request.POST.get('revision'))

            # If a revision ID was passed in the form, get that revision so its
            # date can be referenced in notification messages
            if is_reverting:
                previous_revision = get_object_or_404(
                    page.revisions, id=request.POST.get('revision'))

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()
                # Need to reload the page because the URL may have changed, and we
                # need the up-to-date URL for the "View Live" button.
                page = page.specific_class.objects.get(pk=page.pk)

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    # Page has been scheduled for publishing in the future

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been scheduled for publishing."
                        ).format(
                            previous_revision.created_at.strftime(
                                "%d %b %Y %H:%M"),
                            page.get_admin_display_title())
                    else:
                        message = _(
                            "Page '{0}' has been scheduled for publishing."
                        ).format(page.get_admin_display_title())

                    messages.success(request,
                                     message,
                                     buttons=[
                                         messages.button(
                                             reverse('wagtailadmin_pages:edit',
                                                     args=(page.id, )),
                                             _('Edit'))
                                     ])

                else:
                    # Page is being published now

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been published."
                        ).format(
                            previous_revision.created_at.strftime(
                                "%d %b %Y %H:%M"),
                            page.get_admin_display_title())
                    else:
                        message = _("Page '{0}' has been published.").format(
                            page.get_admin_display_title())

                    messages.success(request,
                                     message,
                                     buttons=[
                                         messages.button(page.url,
                                                         _('View live'),
                                                         new_window=True),
                                         messages.button(
                                             reverse('wagtailadmin_pages:edit',
                                                     args=(page_id, )),
                                             _('Edit'))
                                     ])

            elif is_submitting:

                message = _(
                    "Page '{0}' has been submitted for moderation.").format(
                        page.get_admin_display_title())

                messages.success(request,
                                 message,
                                 buttons=[
                                     messages.button(reverse(
                                         'wagtailadmin_pages:view_draft',
                                         args=(page_id, )),
                                                     _('View draft'),
                                                     new_window=True),
                                     messages.button(
                                         reverse('wagtailadmin_pages:edit',
                                                 args=(page_id, )), _('Edit'))
                                 ])

                if not send_notification(page.get_latest_revision().id,
                                         'submitted', request.user.pk):
                    messages.error(
                        request,
                        _("Failed to send notifications to moderators"))

            else:  # Saving

                if is_reverting:
                    message = _(
                        "Page '{0}' has been replaced with revision from {1}."
                    ).format(
                        page.get_admin_display_title(),
                        previous_revision.created_at.strftime(
                            "%d %b %Y %H:%M"))
                else:
                    message = _("Page '{0}' has been updated.").format(
                        page.get_admin_display_title())

                messages.success(request, message)

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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            if page.locked:
                messages.error(
                    request, _("The page could not be saved as it is locked"))
            else:
                messages.validation_error(
                    request,
                    _("The page could not be saved due to validation errors"),
                    form)

            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.items()
                 if formset.errors]))
            has_unsaved_changes = True
    else:
        form = form_class(instance=page)
        edit_handler = edit_handler_class(instance=page, form=form)
        has_unsaved_changes = False

    # Check for revisions still undergoing moderation and warn
    if latest_revision and latest_revision.submitted_for_moderation:
        buttons = []

        if page.live:
            buttons.append(
                messages.button(
                    reverse('wagtailadmin_pages:revisions_compare',
                            args=(page.id, 'live', latest_revision.id)),
                    _('Compare with live version')))

        messages.warning(request,
                         _("This page is currently awaiting moderation"),
                         buttons=buttons)

    return render(
        request, 'wagtailadmin/pages/edit.html', {
            'page': page,
            'content_type': content_type,
            'edit_handler': edit_handler,
            'errors_debug': errors_debug,
            'preview_modes': page.preview_modes,
            'form': form,
            'next': next_url,
            'has_unsaved_changes': has_unsaved_changes,
        })
Exemplo n.º 15
0
def submit_marketplace_entry(request, marketplace_index):
    form = MarketplaceEntryForm(data=request.POST or None, label_suffix='')

    # If the user uploaded a logo we want the logo_form to validate it is a
    # valid image, but if no logo file was uploaded then proceed with an
    # unbound ImageForm. This avoids re-display due to errors in the main form
    # erroneously telling the user that the logo file is required (it is required
    # for that form, but the entire form is optional).
    if request.FILES:
        logo_form = ImageForm(data=request.POST,
                              files=request.FILES,
                              label_suffix='')
        logo_form_valid = logo_form.is_valid()
    else:
        logo_form = ImageForm(label_suffix='')
        logo_form_valid = True

    if request.method == 'POST' and form.is_valid() and logo_form_valid:
        marketplace_entry_page = form.save(commit=False)
        marketplace_entry_page.slug = slugify(marketplace_entry_page.title)
        marketplace_entry = marketplace_index.add_child(
            instance=marketplace_entry_page)

        if marketplace_entry:
            marketplace_entry.unpublish()
            if request.FILES:
                logo_image = logo_form.save(commit=False)
                logo_image.title = "Logo for %s" % marketplace_entry_page.title
                logo_image.save()
                marketplace_entry.logo_image = logo_image

            for service in request.POST.getlist('services'):
                ServiceMarketplaceEntry.objects.create(
                    service=Service.objects.get(id=service),
                    page=marketplace_entry)
            if request.POST.get('services_additional'):
                for service_name in request.POST.get(
                        'services_additional').split(","):
                    service_name = service_name.lstrip().rstrip().capitalize()
                    service, created = Service.objects.get_or_create(
                        name=service_name)
                    ServiceMarketplaceEntry.objects.create(
                        service=service, page=marketplace_entry)
            for expertise in request.POST.getlist('expertise'):
                ExpertiseMarketplaceEntry.objects.create(
                    expertise=Expertise.objects.get(id=expertise),
                    page=marketplace_entry)
            if request.POST.get('expertise_additional'):
                for expertise_name in request.POST.get(
                        'expertise_additional').split(","):
                    expertise_name = expertise_name.lstrip().rstrip(
                    ).capitalize()
                    expertise, created = Expertise.objects.get_or_create(
                        name=expertise_name)
                    ExpertiseMarketplaceEntry.objects.create(
                        expertise=expertise, page=marketplace_entry)
            for region in request.POST.getlist('regions_experience'):
                RegionMarketplaceEntry.objects.create(
                    region=Region.objects.get(id=region),
                    page=marketplace_entry)
            for country in request.POST.getlist('countries_experience'):
                CountryMarketplaceEntry.objects.create(
                    country=Country.objects.get(id=country),
                    page=marketplace_entry)

            # Submit page for moderation. This requires first saving a revision.
            marketplace_entry.save_revision(submitted_for_moderation=True)
            # Then send the notification. Last param None means do not exclude any
            # moderators from email (internally wagtail would exclude the user
            # submitting from such emails, be we are submitting something from an
            # anonymous user, so no one should be excluded from the email).
            send_notification(marketplace_entry.get_latest_revision().id,
                              'submitted', None)
        return HttpResponseRedirect(
            marketplace_index.url +
            marketplace_index.reverse_subpage('thanks'))

    services = Service.objects.order_by('name')
    expertise_list = Expertise.objects.order_by('name')
    countries = Country.objects.order_by('name')
    regions = Region.objects.order_by('name')
    base_year = datetime.today().year
    years = [base_year - x for x in range(0, 100)]
    context = {
        'form': form,
        'logo_form': logo_form,
        'services': services,
        'years': years,
        'expertise_list': expertise_list,
        'countries': countries,
        'regions': regions,
        'marketplace_index': marketplace_index,
    }
    return render(request, 'portal_pages/marketplace_entry_page_add.html',
                  context)
Exemplo n.º 16
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()

    content_type = ContentType.objects.get_for_model(page)
    page_class = content_type.model_class()

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

    edit_handler_class = page_class.get_edit_handler()
    form_class = edit_handler_class.get_form_class(page_class)

    next_url = get_valid_next_url_from_request(request)

    errors_debug = None

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=page,
                          parent_page=parent)

        if form.is_valid() and not page.locked:
            page = form.save(commit=False)

            is_publishing = bool(request.POST.get('action-publish')) and page_perms.can_publish()
            is_submitting = bool(request.POST.get('action-submit'))
            is_reverting = bool(request.POST.get('revision'))

            # If a revision ID was passed in the form, get that revision so its
            # date can be referenced in notification messages
            if is_reverting:
                previous_revision = get_object_or_404(page.revisions, id=request.POST.get('revision'))

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()
                # Need to reload the page because the URL may have changed, and we
                # need the up-to-date URL for the "View Live" button.
                page = page.specific_class.objects.get(pk=page.pk)

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    # Page has been scheduled for publishing in the future

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been scheduled for publishing."
                        ).format(
                            previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                            page.title
                        )
                    else:
                        message = _(
                            "Page '{0}' has been scheduled for publishing."
                        ).format(
                            page.title
                        )

                    messages.success(request, message, buttons=[
                        messages.button(
                            reverse('wagtailadmin_pages:edit', args=(page.id,)),
                            _('Edit')
                        )
                    ])

                else:
                    # Page is being published now

                    if is_reverting:
                        message = _(
                            "Revision from {0} of page '{1}' has been published."
                        ).format(
                            previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                            page.title
                        )
                    else:
                        message = _(
                            "Page '{0}' has been published."
                        ).format(
                            page.title
                        )

                    messages.success(request, message, buttons=[
                        messages.button(
                            page.url,
                            _('View live')
                        ),
                        messages.button(
                            reverse('wagtailadmin_pages:edit', args=(page_id,)),
                            _('Edit')
                        )
                    ])

            elif is_submitting:

                message = _(
                    "Page '{0}' has been submitted for moderation."
                ).format(
                    page.title
                )

                messages.success(request, message, buttons=[
                    messages.button(
                        reverse('wagtailadmin_pages:view_draft', args=(page_id,)),
                        _('View draft')
                    ),
                    messages.button(
                        reverse('wagtailadmin_pages:edit', args=(page_id,)),
                        _('Edit')
                    )
                ])

                if not send_notification(page.get_latest_revision().id, 'submitted', request.user.pk):
                    messages.error(request, _("Failed to send notifications to moderators"))

            else:  # Saving

                if is_reverting:
                    message = _(
                        "Page '{0}' has been replaced with revision from {1}."
                    ).format(
                        page.title,
                        previous_revision.created_at.strftime("%d %b %Y %H:%M")
                    )
                else:
                    message = _(
                        "Page '{0}' has been updated."
                    ).format(
                        page.title
                    )

                messages.success(request, message)

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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            if page.locked:
                messages.error(request, _("The page could not be saved as it is locked"))
            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.items()
                    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,
        'content_type': content_type,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
        'preview_modes': page.preview_modes,
        'form': form,
        'next': next_url,
    })
Exemplo n.º 17
0
def submit_case_study(request, case_study_index):

    form = CaseStudyForm(data=request.POST or None, label_suffix='')

    # If the user uploaded a flow document we want the flow_json_file_form to validate it is a
    # valid document, but if no file was uploaded then proceed with an
    # unbound FlowJSONFileForm. This avoids re-display due to errors in the main form
    # erroneously telling the user that the flow file is required (it is required
    # for that form, but the entire form is optional).
    if request.FILES:
        flow_json_file_form = FlowJSONFileForm(data=request.POST, files=request.FILES, label_suffix='')
        flow_json_file_form_valid = flow_json_file_form.is_valid()
    else:
        flow_json_file_form = FlowJSONFileForm(label_suffix='')
        flow_json_file_form_valid = True

    if request.method == 'POST' and form.is_valid() and flow_json_file_form_valid:
        case_study_page = form.save(commit=False)
        if request.POST.get('year_start') and request.POST.get('month_start'):
            full_date = request.POST.get('year_start') + '-' + request.POST.get('month_start') + '-01'
            case_study_page.date = datetime.strptime(full_date, '%Y-%m-%d').date()
        case_study_page.slug = slugify(case_study_page.title)
        case_study = case_study_index.add_child(instance=case_study_page)

        if case_study:
            case_study.unpublish()
            if request.FILES:
                downloadable_package = flow_json_file_form.save(commit=False)
                downloadable_package.title = "Document for %s" % case_study_page.title
                downloadable_package.save()
                case_study.downloadable_package = downloadable_package

            for focus_area in request.POST.getlist('focus_areas'):
                FocusAreaCaseStudy.objects.create(
                    focusarea=FocusArea.objects.get(id=focus_area),
                    page=case_study
                )
            if request.POST.get('focus_areas_additional'):
                for focus_area_name in request.POST.get('focus_areas_additional').split(","):
                    focus_area_name = focus_area_name.lstrip().rstrip().capitalize()
                    focus_area, created = FocusArea.objects.get_or_create(name=focus_area_name)
                    FocusAreaCaseStudy.objects.create(
                        focusarea=focus_area,
                        page=case_study
                    )
            for organization in request.POST.getlist('organizations'):
                OrganizationCaseStudy.objects.create(
                    organization=Organization.objects.get(id=organization),
                    page=case_study
                )
            if request.POST.get('organizations_additional'):
                for organization_name in request.POST.get('organizations_additional').split(","):
                    organization_name = organization_name.lstrip().rstrip().capitalize()
                    organization, created = Organization.objects.get_or_create(name=organization_name)
                    OrganizationCaseStudy.objects.create(
                        organization=organization,
                        page=case_study
                    )
            for region in request.POST.getlist('regions'):
                RegionCaseStudy.objects.create(
                    region=Region.objects.get(id=region),
                    page=case_study
                )
            for country in request.POST.getlist('countries'):
                CountryCaseStudy.objects.create(
                    country=Country.objects.get(id=country),
                    page=case_study
                )

            # Submit page for moderation. This requires first saving a revision.
            case_study.save_revision(submitted_for_moderation=True)
            # Then send the notification. Last param None means do not exclude any
            # moderators from email (internally wagtail would exclude the user
            # submitting from such emails, be we are submitting something from an
            # anonymous user, so no one should be excluded from the email).
            send_notification(case_study.get_latest_revision().id, 'submitted', None)
        return HttpResponseRedirect(case_study_index.url + case_study_index.reverse_subpage('thanks'))

    focus_areas = FocusArea.objects.order_by('name')
    organizations = Organization.objects.order_by('name')
    countries = Country.objects.order_by('name')
    regions = Region.objects.order_by('name')
    base_year = datetime.today().year
    years = [base_year - x for x in range(0, 100)]
    months = ['January', 'February', 'March', 'April',
              'May', 'June', 'July', 'August',
              'September', 'October', 'November', 'December']
    months = [('%02d' % x, y) for x, y in list(enumerate(months,1))] # months = [('01', 'Jan'), ('02', 'Feb')], ...
    marketplace_index = MarketplaceIndexPage.objects.live()[0]
    context = {
        'form': form,
        'flow_json_file_form': flow_json_file_form,
        'focus_areas': focus_areas,
        'organizations': organizations,
        'years': years,
        'months': months,
        'countries': countries,
        'regions': regions,
        'case_study_index': case_study_index,
        'marketplace_index': marketplace_index,
    }
    return render(request, 'portal_pages/case_study_page_add.html', context)
Exemplo n.º 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()

    content_type = ContentType.objects.get_for_model(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)

        # 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

        # Validate title and seo_title are not entirely whitespace
        def clean_title(title):
            validate_not_whitespace(title)
            return title
        form.fields['title'].clean = clean_title

        def clean_seo_title(seo_title):
            if not seo_title:
                return ''
            validate_not_whitespace(seo_title)
            return seo_title

        form.fields['seo_title'].clean = clean_seo_title

        # 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() and not page.locked:
            page = form.save(commit=False)

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

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()
            else:
                # Set has_unpublished_changes flag
                if page.live:
                    # To avoid overwriting the live version, we only save the page
                    # to the revisions table
                    Page.objects.filter(id=page.id).update(has_unpublished_changes=True)
                else:
                    page.has_unpublished_changes = True
                    page.save()

            # Notifications
            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title), buttons=[
                    messages.button(page.url, _('View live')),
                    messages.button(reverse('wagtailadmin_pages_edit', args=(page_id,)), _('Edit'))
                ])
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title), buttons=[
                    messages.button(reverse('wagtailadmin_pages_view_draft', args=(page_id,)), _('View draft')),
                    messages.button(reverse('wagtailadmin_pages_edit', args=(page_id,)), _('Edit'))
                ])
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages_edit', page.id)
        else:
            if page.locked:
                messages.error(request, _("The page could not be saved as it is locked"))
            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.items() 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,
        'content_type': content_type,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
        'preview_modes': page.preview_modes,
        'form': form, # Used in unit tests
    })
Exemplo n.º 19
0
def confirm_page_reversion(request, revision_id, template_name='wagtailrollbacks/pages/confirm_reversion.html'):
    """
    Handles page reversion process (GET and POST).

    :param request: the request instance.
    :param revision_id: the page revision ID.
    :param template_name: the template name.
    :rtype: django.http.HttpResponse.
    """
    revision    = get_object_or_404(PageRevision, pk=revision_id)
    page        = revision.page

    if page.locked:
        messages.error(
            request,
            _("Page '{0}' is locked.").format(page.title),
            buttons = []
        )

        return redirect(reverse('wagtailadmin_pages:edit', args=(page.id,)))

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

    if request.POST:
        is_publishing   = bool(request.POST.get('action-publish')) and page_perms.can_publish()
        is_submitting   = bool(request.POST.get('action-submit'))
        new_revision    = page.rollback(
            revision_id                 = revision_id,
            user                        = request.user,
            submitted_for_moderation    = is_submitting
        )

        if is_publishing:
            new_revision.publish()

            messages.success(
                request,
                _("Page '{0}' published.").format(page.title),
                buttons=[
                    messages.button(page.url, _('View live')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                ]
            )
        elif is_submitting:
            messages.success(
                request,
                _("Page '{0}' submitted for moderation.").format(page.title),
                buttons=[
                    messages.button(reverse('wagtailadmin_pages:view_draft', args=(page.id,)), _('View draft')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                ]
            )
            send_notification(new_revision.id, 'submitted', request.user.id)
        else:
            messages.success(
                request,
                _("Page '{0}' updated.").format(page.title),
                buttons=[]
            )

        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)

    return render(
        request,
        template_name,
        {
            'page':         page,
            'revision':     revision,
            'page_perms':   page_perms
        }
    )
Exemplo n.º 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

    # 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.allowed_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

        # Validate title and seo_title are not entirely whitespace
        def clean_title(title):
            validate_not_whitespace(title)
            return title

        form.fields['title'].clean = clean_title

        def clean_seo_title(seo_title):
            if not seo_title:
                return ''
            validate_not_whitespace(seo_title)
            return seo_title

        form.fields['seo_title'].clean = clean_seo_title

        # 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)

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

            # Set live to False and has_unpublished_changes to True if we are not publishing
            if not is_publishing:
                page.live = False
                page.has_unpublished_changes = True

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            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))
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages_edit', page.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,
            'preview_modes': page.preview_modes,
            'form': form,  # Used in unit tests
        })
Exemplo n.º 21
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 page_class not in parent_page.creatable_subpage_models():
        raise PermissionDenied

    if not page_class.can_create_at(parent_page):
        raise PermissionDenied

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

    next_url = get_valid_next_url_from_request(request)

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

        if form.is_valid():
            page = form.save(commit=False)

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

            if not is_publishing:
                page.live = False

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    messages.success(request, _("Page '{0}' created and scheduled for publishing.").format(page.title), buttons=[
                        messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                    ])
                else:
                    messages.success(request, _("Page '{0}' created and published.").format(page.title), buttons=[
                        messages.button(page.url, _('View live')),
                        messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                    ])
            elif is_submitting:
                messages.success(
                    request,
                    _("Page '{0}' created and submitted for moderation.").format(page.title),
                    buttons=[
                        messages.button(reverse('wagtailadmin_pages:view_draft', args=(page.id,)), _('View draft')),
                        messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit'))
                    ]
                )
                if not send_notification(page.get_latest_revision().id, 'submitted', request.user.pk):
                    messages.error(request, _("Failed to send notifications to moderators"))
            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

            if is_publishing or is_submitting:
                # we're done here
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            messages.error(request, _("The page could not be created due to validation errors"))
            edit_handler = edit_handler_class(instance=page, form=form)
            has_unsaved_changes = True
    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)
        has_unsaved_changes = False

    return render(request, 'wagtailadmin/pages/create.html', {
        'content_type': content_type,
        'page_class': page_class,
        'parent_page': parent_page,
        'edit_handler': edit_handler,
        'preview_modes': page.preview_modes,
        'form': form,
        'next': next_url,
        'has_unsaved_changes': has_unsaved_changes,
    })
Exemplo n.º 22
0
def submit_marketplace_entry(request, marketplace_index):
    form = MarketplaceEntryForm(data=request.POST or None, label_suffix='')

    # If the user uploaded a logo we want the logo_form to validate it is a
    # valid image, but if no logo file was uploaded then proceed with an
    # unbound ImageForm. This avoids re-display due to errors in the main form
    # erroneously telling the user that the logo file is required (it is required
    # for that form, but the entire form is optional).
    if request.FILES:
        logo_form = ImageForm(data=request.POST, files=request.FILES, label_suffix='')
        logo_form_valid = logo_form.is_valid()
    else:
        logo_form = ImageForm(label_suffix='')
        logo_form_valid = True

    if request.method == 'POST' and form.is_valid() and logo_form_valid:
        marketplace_entry_page = form.save(commit=False)
        marketplace_entry_page.slug = slugify(marketplace_entry_page.title)
        marketplace_entry = marketplace_index.add_child(instance=marketplace_entry_page)

        if marketplace_entry:
            marketplace_entry.unpublish()
            if request.FILES:
                logo_image = logo_form.save(commit=False)
                logo_image.title = "Logo for %s" % marketplace_entry_page.title
                logo_image.save()
                marketplace_entry.logo_image = logo_image

            for service in request.POST.getlist('services'):
                ServiceMarketplaceEntry.objects.create(
                    service=Service.objects.get(id=service),
                    page=marketplace_entry
                )
            if request.POST.get('services_additional'):
                for service_name in request.POST.get('services_additional').split(","):
                    service_name = service_name.lstrip().rstrip().capitalize()
                    service, created = Service.objects.get_or_create(name=service_name)
                    ServiceMarketplaceEntry.objects.create(
                        service=service,
                        page=marketplace_entry
                    )
            for expertise in request.POST.getlist('expertise'):
                ExpertiseMarketplaceEntry.objects.create(
                    expertise=Expertise.objects.get(id=expertise),
                    page=marketplace_entry
                )
            if request.POST.get('expertise_additional'):
                for expertise_name in request.POST.get('expertise_additional').split(","):
                    expertise_name = expertise_name.lstrip().rstrip().capitalize()
                    expertise, created = Expertise.objects.get_or_create(name=expertise_name)
                    ExpertiseMarketplaceEntry.objects.create(
                        expertise=expertise,
                        page=marketplace_entry
                    )
            for region in request.POST.getlist('regions_experience'):
                RegionMarketplaceEntry.objects.create(
                    region=Region.objects.get(id=region),
                    page=marketplace_entry
                )
            for country in request.POST.getlist('countries_experience'):
                CountryMarketplaceEntry.objects.create(
                    country=Country.objects.get(id=country),
                    page=marketplace_entry
                )

            # Submit page for moderation. This requires first saving a revision.
            marketplace_entry.save_revision(submitted_for_moderation=True)
            # Then send the notification. Last param None means do not exclude any
            # moderators from email (internally wagtail would exclude the user
            # submitting from such emails, be we are submitting something from an
            # anonymous user, so no one should be excluded from the email).
            send_notification(marketplace_entry.get_latest_revision().id, 'submitted', None)
        return HttpResponseRedirect(marketplace_index.url + marketplace_index.reverse_subpage('thanks'))

    services = Service.objects.order_by('name')
    expertise_list = Expertise.objects.order_by('name')
    countries = Country.objects.order_by('name')
    regions = Region.objects.order_by('name')
    base_year = datetime.today().year
    years = [base_year - x for x in range(0, 100)]
    context = {
        'form': form,
        'logo_form': logo_form,
        'services': services,
        'years': years,
        'expertise_list': expertise_list,
        'countries': countries,
        'regions': regions,
        'marketplace_index': marketplace_index,
    }
    return render(request, 'portal_pages/marketplace_entry_page_add.html', context)
Exemplo n.º 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()
    parent = page.get_parent()

    content_type = ContentType.objects.get_for_model(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)
        validate_page_form(form, parent, page)

        if form.is_valid() and not page.locked:
            page = form.save(commit=False)

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

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                messages.success(request, _("Page '{0}' published.").format(page.title), buttons=[
                    messages.button(page.url, _('View live')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(page_id,)), _('Edit'))
                ])
            elif is_submitting:
                messages.success(request, _("Page '{0}' submitted for moderation.").format(page.title), buttons=[
                    messages.button(reverse('wagtailadmin_pages:view_draft', args=(page_id,)), _('View draft')),
                    messages.button(reverse('wagtailadmin_pages:edit', args=(page_id,)), _('Edit'))
                ])
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages:edit', page.id)
        else:
            if page.locked:
                messages.error(request, _("The page could not be saved as it is locked"))
            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.items() 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,
        'content_type': content_type,
        'edit_handler': edit_handler,
        'errors_debug': errors_debug,
        'preview_modes': page.preview_modes,
        'form': form, # Used in unit tests
    })
Exemplo n.º 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

    # 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 page_class not in parent_page.creatable_subpage_models():
        raise PermissionDenied

    if not page_class.can_create_at(parent_page):
        raise PermissionDenied

    for fn in hooks.get_hooks('before_create_page'):
        result = fn(request, parent_page, page_class)
        if hasattr(result, 'status_code'):
            return result

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

    next_url = get_valid_next_url_from_request(request)

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

        if form.is_valid():
            page = form.save(commit=False)

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

            if not is_publishing:
                page.live = False

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            if is_publishing:
                if page.go_live_at and page.go_live_at > timezone.now():
                    messages.success(
                        request,
                        _("Page '{0}' created and scheduled for publishing."
                          ).format(page.get_admin_display_title()),
                        buttons=[
                            messages.button(
                                reverse('wagtailadmin_pages:edit',
                                        args=(page.id, )), _('Edit'))
                        ])
                else:
                    messages.success(
                        request,
                        _("Page '{0}' created and published.").format(
                            page.get_admin_display_title()),
                        buttons=[
                            messages.button(page.url,
                                            _('View live'),
                                            new_window=True),
                            messages.button(
                                reverse('wagtailadmin_pages:edit',
                                        args=(page.id, )), _('Edit'))
                        ])
            elif is_submitting:
                messages.success(
                    request,
                    _("Page '{0}' created and submitted for moderation."
                      ).format(page.get_admin_display_title()),
                    buttons=[
                        messages.button(reverse(
                            'wagtailadmin_pages:view_draft', args=(page.id, )),
                                        _('View draft'),
                                        new_window=True),
                        messages.button(
                            reverse('wagtailadmin_pages:edit',
                                    args=(page.id, )), _('Edit'))
                    ])
                if not send_notification(page.get_latest_revision().id,
                                         'submitted', request.user.pk):
                    messages.error(
                        request,
                        _("Failed to send notifications to moderators"))
            else:
                messages.success(
                    request,
                    _("Page '{0}' created.").format(
                        page.get_admin_display_title()))

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

            if is_publishing or is_submitting:
                # we're done here
                if next_url:
                    # redirect back to 'next' url if present
                    return redirect(next_url)
                # redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                target_url = reverse('wagtailadmin_pages:edit', args=[page.id])
                if next_url:
                    # Ensure the 'next' url is passed through again if present
                    target_url += '?next=%s' % urlquote(next_url)
                return redirect(target_url)
        else:
            messages.validation_error(
                request,
                _("The page could not be created due to validation errors"),
                form)
            edit_handler = edit_handler_class(instance=page, form=form)
            has_unsaved_changes = True
    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)
        has_unsaved_changes = False

    return render(
        request, 'wagtailadmin/pages/create.html', {
            'content_type': content_type,
            'page_class': page_class,
            'parent_page': parent_page,
            'edit_handler': edit_handler,
            'preview_modes': page.preview_modes,
            'form': form,
            'next': next_url,
            'has_unsaved_changes': has_unsaved_changes,
        })
Exemplo n.º 25
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.allowed_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

        # Validate title and seo_title are not entirely whitespace
        def clean_title(title):
            validate_not_whitespace(title)
            return title
        form.fields['title'].clean = clean_title

        def clean_seo_title(seo_title):
            if not seo_title:
                return ''
            validate_not_whitespace(seo_title)
            return seo_title
        form.fields['seo_title'].clean = clean_seo_title

        # 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)

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

            # Set live to False and has_unpublished_changes to True if we are not publishing
            if not is_publishing:
                page.live = False
                page.has_unpublished_changes = True

            # Save page
            parent_page.add_child(instance=page)

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()

            # Notifications
            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))
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages_edit', page.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,
        'preview_modes': page.preview_modes,
        'form': form, # Used in unit tests
    })
Exemplo n.º 26
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()

    content_type = ContentType.objects.get_for_model(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)

        # 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

        # Validate title and seo_title are not entirely whitespace
        def clean_title(title):
            validate_not_whitespace(title)
            return title

        form.fields['title'].clean = clean_title

        def clean_seo_title(seo_title):
            if not seo_title:
                return ''
            validate_not_whitespace(seo_title)
            return seo_title

        form.fields['seo_title'].clean = clean_seo_title

        # 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() and not page.locked:
            page = form.save(commit=False)

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

            # Save revision
            revision = page.save_revision(
                user=request.user,
                submitted_for_moderation=is_submitting,
            )

            # Publish
            if is_publishing:
                revision.publish()
            else:
                # Set has_unpublished_changes flag
                if page.live:
                    # To avoid overwriting the live version, we only save the page
                    # to the revisions table
                    Page.objects.filter(id=page.id).update(
                        has_unpublished_changes=True)
                else:
                    page.has_unpublished_changes = True
                    page.save()

            # Notifications
            if is_publishing:
                messages.success(request,
                                 _("Page '{0}' published.").format(page.title),
                                 buttons=[
                                     messages.button(page.url, _('View live')),
                                     messages.button(
                                         reverse('wagtailadmin_pages_edit',
                                                 args=(page_id, )), _('Edit'))
                                 ])
            elif is_submitting:
                messages.success(
                    request,
                    _("Page '{0}' submitted for moderation.").format(
                        page.title),
                    buttons=[
                        messages.button(
                            reverse('wagtailadmin_pages_view_draft',
                                    args=(page_id, )), _('View draft')),
                        messages.button(
                            reverse('wagtailadmin_pages_edit',
                                    args=(page_id, )), _('Edit'))
                    ])
                send_notification(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

            if is_publishing or is_submitting:
                # we're done here - redirect back to the explorer
                return redirect('wagtailadmin_explore', page.get_parent().id)
            else:
                # Just saving - remain on edit page for further edits
                return redirect('wagtailadmin_pages_edit', page.id)
        else:
            if page.locked:
                messages.error(
                    request, _("The page could not be saved as it is locked"))
            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.items()
                 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,
            'content_type': content_type,
            'edit_handler': edit_handler,
            'errors_debug': errors_debug,
            'preview_modes': page.preview_modes,
            'form': form,  # Used in unit tests
        })