Example #1
0
def add(request, media_type):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    if request.POST:
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(request.POST, request.FILES, instance=media, user=request.user)
        if form.is_valid():
            form.save()

            # Reindex the media entry to make sure all tags are indexed
            for backend in get_search_backends():
                backend.add(media)

            messages.success(request, _("Media file '{0}' added.").format(media.title), buttons=[
                messages.button(reverse('wagtailmedia:edit', args=(media.id,)), _('Edit'))
            ])
            return redirect('wagtailmedia:index')
        else:
            messages.error(request, _("The media file could not be saved due to errors."))
    else:
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(user=request.user, instance=media)

    return render(request, "wagtailmedia/media/add.html", {
        'form': form,
        'media_type': media_type,
    })
Example #2
0
def add(request):
    if request.method == 'POST':
        # Get query
        query_form = search_forms.QueryForm(request.POST)
        if query_form.is_valid():
            query = Query.get(query_form['query_string'].value())

            # Save search picks
            searchpicks_formset = forms.SearchPromotionsFormSet(request.POST, instance=query)
            if save_searchpicks(query, query, searchpicks_formset):
                messages.success(request, _("Editor's picks for '{0}' created.").format(query), buttons=[
                    messages.button(reverse('wagtailsearchpromotions:edit', args=(query.id,)), _('Edit'))
                ])
                return redirect('wagtailsearchpromotions:index')
            else:
                if len(searchpicks_formset.non_form_errors()):
                    # formset level error (e.g. no forms submitted)
                    messages.error(request, " ".join(error for error in searchpicks_formset.non_form_errors()))
                else:
                    # specific errors will be displayed within form fields
                    messages.error(request, _("Recommendations have not been created due to errors"))
        else:
            searchpicks_formset = forms.SearchPromotionsFormSet()
    else:
        query_form = search_forms.QueryForm()
        searchpicks_formset = forms.SearchPromotionsFormSet()

    return render(request, 'wagtailsearchpromotions/add.html', {
        'query_form': query_form,
        'searchpicks_formset': searchpicks_formset,
        'form_media': query_form.media + searchpicks_formset.media,
    })
Example #3
0
def index(request):

    form = SearchForm(placeholder=_("Search something"))

    example_form = ExampleForm()

    messages.success(request, _("Success message"), buttons=[
        messages.button('', _('View live')),
        messages.button('', _('Edit'))
    ])
    messages.warning(request, _("Warning message"), buttons=[
        messages.button('', _('View live')),
        messages.button('', _('Edit'))
    ])
    messages.error(request, _("Error message"), buttons=[
        messages.button('', _('View live')),
        messages.button('', _('Edit'))
    ])

    paginator = Paginator(list(range(100)), 10)
    page = paginator.page(2)

    user = User(email='*****@*****.**')

    return render(request, 'wagtailstyleguide/base.html', {
        'search_form': form,
        'example_form': example_form,
        'example_page': page,
        'user': user,
    })
Example #4
0
def add(request):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    if request.method == 'POST':
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image, user=request.user)
        if form.is_valid():
            # Set image file size
            image.file_size = image.file.size

            form.save()

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

            messages.success(request, _("Image '{0}' added.").format(image.title), buttons=[
                messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit'))
            ])
            return redirect('wagtailimages:index')
        else:
            messages.error(request, _("The image could not be created due to errors."))
    else:
        form = ImageForm(user=request.user)

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
    })
Example #5
0
def edit(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    can_delete = user_can_delete_user(request.user, user)
    editing_self = request.user == user

    for fn in hooks.get_hooks('before_edit_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_edit_form()(request.POST, request.FILES, instance=user, editing_self=editing_self)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("User '{0}' updated.").format(user), buttons=[
                messages.button(reverse('wagtailusers_users:edit', args=(user.pk,)), _('Edit'))
            ])
            for fn in hooks.get_hooks('after_edit_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be saved due to errors."))
    else:
        form = get_user_edit_form()(instance=user, editing_self=editing_self)

    return render(request, 'wagtailusers/users/edit.html', {
        'user': user,
        'form': form,
        'can_delete': can_delete,
    })
Example #6
0
def create(request):
    for fn in hooks.get_hooks('before_create_user'):
        result = fn(request)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_creation_form()(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("User '{0}' created.").format(user), buttons=[
                messages.button(reverse('wagtailusers_users:edit', args=(user.pk,)), _('Edit'))
            ])
            for fn in hooks.get_hooks('after_create_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be created due to errors."))
    else:
        form = get_user_creation_form()()

    return render(request, 'wagtailusers/users/create.html', {
        'form': form,
    })
Example #7
0
def add(request):
    Document = get_document_model()
    DocumentForm = get_document_form(Document)

    if request.method == 'POST':
        doc = Document(uploaded_by_user=request.user)
        form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user)
        if form.is_valid():
            doc.file_size = doc.file.size

            form.save()

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

            messages.success(request, _("Document '{0}' added.").format(doc.title), buttons=[
                messages.button(reverse('wagtaildocs:edit', args=(doc.id,)), _('Edit'))
            ])
            return redirect('wagtaildocs:index')
        else:
            messages.error(request, _("The document could not be saved due to errors."))
    else:
        form = DocumentForm(user=request.user)

    return render(request, "wagtaildocs/documents/add.html", {
        'form': form,
    })
Example #8
0
    def post(self, request, *args, **kwargs):
        if not request.user.email:
            messages.error(
                request, _(
                    "Your email address is not configured. "
                    "Please update it before exporting."))
            return redirect(request.path)

        drf__date_joined__gte = request.GET.get('drf__date_joined__gte')
        drf__date_joined__lte = request.GET.get('drf__date_joined__lte')
        is_active_exact = request.GET.get('is_active__exact')

        filter_list = {
            'date_joined__range': (drf__date_joined__gte,
                                   drf__date_joined__lte) if
            drf__date_joined__gte and drf__date_joined__lte else None,
            'is_active': is_active_exact
        }

        arguments = {'profile__site': request.site.pk}

        for key, value in filter_list.items():
            if value:
                arguments[key] = value
        self.send_export_email_to_celery(request.user.email, arguments)
        messages.success(request, _(
            "CSV emailed to '{0}'").format(request.user.email))
        return redirect(request.path)
Example #9
0
def edit(request, redirect_id):
    theredirect = get_object_or_404(models.Redirect, id=redirect_id)

    if not permission_policy.user_has_permission_for_instance(
        request.user, 'change', theredirect
    ):
        return permission_denied(request)

    if request.method == 'POST':
        form = RedirectForm(request.POST, request.FILES, instance=theredirect)
        if form.is_valid():
            form.save()
            messages.success(request, _("Redirect '{0}' updated.").format(theredirect.title), buttons=[
                messages.button(reverse('wagtailredirects:edit', args=(theredirect.id,)), _('Edit'))
            ])
            return redirect('wagtailredirects:index')
        else:
            messages.error(request, _("The redirect could not be saved due to errors."))
    else:
        form = RedirectForm(instance=theredirect)

    return render(request, "wagtailredirects/edit.html", {
        'redirect': theredirect,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission(request.user, 'delete'),
    })
Example #10
0
def create(request):
    group = Group()
    if request.method == 'POST':
        form = CSVGroupCreationForm(
            request.POST, request.FILES, instance=group)
        if form.is_valid():
            form.save()

            messages.success(
                request,
                _("Group '{0}' created. "
                  "Imported {1} user(s).").format(
                    group, group.user_set.count()),
                buttons=[
                    messages.button(reverse('wagtailusers_groups:edit',
                                            args=(group.id,)), _('Edit'))
                ]
            )
            return redirect('wagtailusers_groups:index')

        messages.error(request, _(
            "The group could not be created due to errors."))
    else:
        form = CSVGroupCreationForm(instance=group)

    return render(request, 'csv_group_creation/create.html', {
        'form': form
    })
Example #11
0
def edit(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    can_delete = user_can_delete_user(request.user, user)
    editing_self = request.user == user

    for fn in hooks.get_hooks('before_edit_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_edit_form()(request.POST, request.FILES, instance=user, editing_self=editing_self)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("Your details have been updated. You've been logged out for security reasons, "
                                        "please login to continue."))
            for fn in hooks.get_hooks('after_edit_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be saved due to errors."))
    else:
        form = get_user_edit_form()(instance=user, editing_self=editing_self)

    return render(request, 'wagtailusers/users/edit.html', {
        'user': user,
        'form': form,
        'can_delete': can_delete,
    })
Example #12
0
def edit_current_site(request, app_name, model_name):
    # Redirect the user to the edit page for the current site
    # (or the current request does not correspond to a site, the first site in the list)
    site = request.site or Site.objects.first()
    if not site:
        messages.error(request, _("This setting could not be opened because there is no site defined."))
        return redirect('wagtailadmin_home')
    return redirect('wagtailsettings:edit', app_name, model_name, site.pk)
Example #13
0
def edit(request, media_id):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    media = get_object_or_404(Media, id=media_id)

    if not permission_policy.user_has_permission_for_instance(request.user, 'change', media):
        return permission_denied(request)

    if request.POST:
        original_file = media.file
        form = MediaForm(request.POST, request.FILES, instance=media, user=request.user)
        if form.is_valid():
            if 'file' in form.changed_data:
                # if providing a new media file, delete the old one.
                # NB Doing this via original_file.delete() clears the file field,
                # which definitely isn't what we want...
                original_file.storage.delete(original_file.name)
            media = form.save()

            # Reindex the media entry to make sure all tags are indexed
            for backend in get_search_backends():
                backend.add(media)

            messages.success(request, _("Media file '{0}' updated").format(media.title), buttons=[
                messages.button(reverse('wagtailmedia:edit', args=(media.id,)), _('Edit'))
            ])
            return redirect('wagtailmedia:index')
        else:
            messages.error(request, _("The media could not be saved due to errors."))
    else:
        form = MediaForm(instance=media, user=request.user)

    filesize = None

    # Get file size when there is a file associated with the Media object
    if media.file:
        try:
            filesize = media.file.size
        except OSError:
            # File doesn't exist
            pass

    if not filesize:
        messages.error(
            request,
            _("The file could not be found. Please change the source or delete the media file"),
            buttons=[messages.button(reverse('wagtailmedia:delete', args=(media.id,)), _('Delete'))]
        )

    return render(request, "wagtailmedia/media/edit.html", {
        'media': media,
        'filesize': filesize,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', media
        ),
    })
Example #14
0
def permission_denied(request):
    """Return a standard 'permission denied' response"""
    if request.is_ajax():
        raise PermissionDenied

    from wagtail.admin import messages

    messages.error(request, _('Sorry, you do not have permission to access this area.'))
    return redirect('wagtailadmin_home')
Example #15
0
def edit(request, document_id):
    Document = get_document_model()
    DocumentForm = get_document_form(Document)

    doc = get_object_or_404(Document, id=document_id)

    if not permission_policy.user_has_permission_for_instance(request.user, 'change', doc):
        return permission_denied(request)

    if request.method == 'POST':
        original_file = doc.file
        form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user)
        if form.is_valid():
            doc = form.save()
            if 'file' in form.changed_data:
                doc.file_size = doc.file.size

                # if providing a new document file, delete the old one.
                # NB Doing this via original_file.delete() clears the file field,
                # which definitely isn't what we want...
                original_file.storage.delete(original_file.name)

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

            messages.success(request, _("Document '{0}' updated").format(doc.title), buttons=[
                messages.button(reverse('wagtaildocs:edit', args=(doc.id,)), _('Edit'))
            ])
            return redirect('wagtaildocs:index')
        else:
            messages.error(request, _("The document could not be saved due to errors."))
    else:
        form = DocumentForm(instance=doc, user=request.user)

    try:
        local_path = doc.file.path
    except NotImplementedError:
        # Document is hosted externally (eg, S3)
        local_path = None

    if local_path:
        # Give error if document file doesn't exist
        if not os.path.isfile(local_path):
            messages.error(
                request,
                _("The file could not be found. Please change the source or delete the document"),
                buttons=[messages.button(reverse('wagtaildocs:delete', args=(doc.id,)), _('Delete'))]
            )

    return render(request, "wagtaildocs/documents/edit.html", {
        'document': doc,
        'filesize': doc.get_file_size(),
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', doc
        ),
    })
Example #16
0
def edit(request, app_name, model_name, site_pk):
    model = get_model_from_url_params(app_name, model_name)
    if not user_can_edit_setting_type(request.user, model):
        raise PermissionDenied
    site = get_object_or_404(Site, pk=site_pk)

    setting_type_name = model._meta.verbose_name

    instance = model.for_site(site)
    edit_handler = get_setting_edit_handler(model)
    form_class = edit_handler.get_form_class()

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

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

            messages.success(
                request,
                _("{setting_type} updated.").format(
                    setting_type=capfirst(setting_type_name),
                    instance=instance
                )
            )
            return redirect('wagtailsettings:edit', app_name, model_name, site.pk)
        else:
            messages.error(request, _("The setting could not be saved due to errors."))
            edit_handler = edit_handler.bind_to_instance(
                instance=instance, form=form)
    else:
        form = form_class(instance=instance)
        edit_handler = edit_handler.bind_to_instance(
            instance=instance, form=form)

    # Show a site switcher form if there are multiple sites
    site_switcher = None
    if Site.objects.count() > 1:
        site_switcher = SiteSwitchForm(site, model)

    return render(request, 'wagtailsettings/edit.html', {
        'opts': model._meta,
        'setting_type_name': setting_type_name,
        'instance': instance,
        'edit_handler': edit_handler,
        'form': form,
        'site': site,
        'site_switcher': site_switcher,
        'tabbed': isinstance(edit_handler, TabbedInterface),
    })
    def decorated_view(request, *args, **kwargs):
        user = request.user

        if user.is_anonymous:
            return reject_request(request)

        if user.has_perms(['wagtailadmin.access_admin']):
            if hasattr(user, 'wagtail_userprofile'):
                activate_lang(user.wagtail_userprofile.get_preferred_language())
            return view_func(request, *args, **kwargs)

        if not request.is_ajax():
            messages.error(request, _('You do not have permission to access the admin'))

        return reject_request(request)
Example #18
0
def preview_for_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')

    page = revision.as_page_object()

    request.revision_id = revision_id

    # pass in the real user request rather than page.dummy_request(), so that request.user
    # and request.revision_id will be picked up by the wagtail user bar
    return page.serve_preview(request, page.default_preview_mode)
Example #19
0
def edit(request, app_label, model_name, pk,
         template='wagtailsnippets/snippets/edit.html',
         redirect_to=_redirect_to):
    model = get_snippet_model_from_url_params(app_label, model_name)

    permission = get_permission_name('change', model)
    if not request.user.has_perm(permission):
        return permission_denied(request)

    instance = get_object_or_404(model, pk=unquote(pk))
    edit_handler = get_snippet_edit_handler(model)
    form_class = edit_handler.get_form_class()

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

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

            messages.success(
                request,
                _("{snippet_type} '{instance}' updated.").format(
                    snippet_type=capfirst(model._meta.verbose_name_plural),
                    instance=instance
                ),
                buttons=[
                    messages.button(reverse(
                        'wagtailsnippets:edit', args=(app_label, model_name, quote(instance.pk))
                    ), _('Edit'))
                ]
            )
            return redirect_to(app_label, model_name)
        else:
            messages.error(request, _("The snippet could not be saved due to errors."))
            edit_handler = edit_handler.bind_to_instance(instance=instance,
                                                         form=form)
    else:
        form = form_class(instance=instance)
        edit_handler = edit_handler.bind_to_instance(instance=instance,
                                                     form=form)

    return render(request, template, {
        'model_opts': model._meta,
        'instance': instance,
        'edit_handler': edit_handler,
        'form': form,
    })
Example #20
0
def create(request, app_label, model_name):
    model = get_snippet_model_from_url_params(app_label, model_name)

    permission = get_permission_name('add', model)
    if not request.user.has_perm(permission):
        return permission_denied(request)

    instance = model()
    edit_handler = get_snippet_edit_handler(model)
    form_class = edit_handler.get_form_class()

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

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

            messages.success(
                request,
                _("{snippet_type} '{instance}' created.").format(
                    snippet_type=capfirst(model._meta.verbose_name),
                    instance=instance
                ),
                buttons=[
                    messages.button(reverse(
                        'wagtailsnippets:edit', args=(app_label, model_name, quote(instance.pk))
                    ), _('Edit'))
                ]
            )
            return redirect('wagtailsnippets:list', app_label, model_name)
        else:
            messages.error(request, _("The snippet could not be created due to errors."))
            edit_handler = edit_handler.bind_to_instance(instance=instance,
                                                         form=form,
                                                         request=request)
    else:
        form = form_class(instance=instance)
        edit_handler = edit_handler.bind_to_instance(instance=instance,
                                                     form=form,
                                                     request=request)

    return render(request, 'wagtailsnippets/snippets/create.html', {
        'model_opts': model._meta,
        'edit_handler': edit_handler,
        'form': form,
    })
Example #21
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')
Example #22
0
def add(request):
    if request.method == 'POST':
        form = RedirectForm(request.POST, request.FILES)
        if form.is_valid():
            theredirect = form.save()

            messages.success(request, _("Redirect '{0}' added.").format(theredirect.title), buttons=[
                messages.button(reverse('wagtailredirects:edit', args=(theredirect.id,)), _('Edit'))
            ])
            return redirect('wagtailredirects:index')
        else:
            messages.error(request, _("The redirect could not be created due to errors."))
    else:
        form = RedirectForm()

    return render(request, "wagtailredirects/add.html", {
        'form': form,
    })
Example #23
0
def create(request, app_label, model_name):
    model = get_snippet_model_from_url_params(app_label, model_name)

    permission = get_permission_name('add', model)
    if not request.user.has_perm(permission):
        return permission_denied(request)

    instance = model()
    edit_handler_class = get_snippet_edit_handler(model)
    form_class = edit_handler_class.get_form_class(model)

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

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

            messages.success(request,
                             _("{snippet_type} '{instance}' created.").format(
                                 snippet_type=capfirst(
                                     model._meta.verbose_name),
                                 instance=instance),
                             buttons=[
                                 messages.button(
                                     reverse('wagtailsnippets:edit',
                                             args=(app_label, model_name,
                                                   quote(instance.pk))),
                                     _('Edit'))
                             ])
            return redirect('wagtailsnippets:list', app_label, model_name)
        else:
            messages.error(
                request, _("The snippet could not be created due to errors."))
            edit_handler = edit_handler_class(instance=instance, form=form)
    else:
        form = form_class(instance=instance)
        edit_handler = edit_handler_class(instance=instance, form=form)

    return render(request, 'wagtailsnippets/snippets/create.html', {
        'model_opts': model._meta,
        'edit_handler': edit_handler,
        'form': form,
    })
Example #24
0
def index(request):

    form = SearchForm(placeholder=_("Search something"))

    example_form = ExampleForm()

    messages.success(
        request,
        _("Success message"),
        buttons=[
            messages.button("", _("View live")),
            messages.button("", _("Edit"))
        ],
    )
    messages.warning(
        request,
        _("Warning message"),
        buttons=[
            messages.button("", _("View live")),
            messages.button("", _("Edit"))
        ],
    )
    messages.error(
        request,
        _("Error message"),
        buttons=[
            messages.button("", _("View live")),
            messages.button("", _("Edit"))
        ],
    )

    paginator = Paginator(list(range(100)), 10)
    page = paginator.page(2)

    return TemplateResponse(
        request,
        "wagtailstyleguide/base.html",
        {
            "search_form": form,
            "example_form": example_form,
            "example_page": page,
        },
    )
Example #25
0
def add(request):
    if request.method == 'POST':
        # Get query
        query_form = search_forms.QueryForm(request.POST)
        if query_form.is_valid():
            query = Query.get(query_form['query_string'].value())

            # Save search picks
            searchpicks_formset = forms.SearchPromotionsFormSet(request.POST,
                                                                instance=query)
            if save_searchpicks(query, query, searchpicks_formset):
                messages.success(
                    request,
                    _("Editor's picks for '{0}' created.").format(query),
                    buttons=[
                        messages.button(
                            reverse('wagtailsearchpromotions:edit',
                                    args=(query.id, )), _('Edit'))
                    ])
                return redirect('wagtailsearchpromotions:index')
            else:
                if len(searchpicks_formset.non_form_errors()):
                    # formset level error (e.g. no forms submitted)
                    messages.error(
                        request,
                        " ".join(error for error in
                                 searchpicks_formset.non_form_errors()))
                else:
                    # specific errors will be displayed within form fields
                    messages.error(
                        request,
                        _("Recommendations have not been created due to errors"
                          ))
        else:
            searchpicks_formset = forms.SearchPromotionsFormSet()
    else:
        query_form = search_forms.QueryForm()
        searchpicks_formset = forms.SearchPromotionsFormSet()

    return render(request, 'wagtailsearchpromotions/add.html', {
        'query_form': query_form,
        'searchpicks_formset': searchpicks_formset,
    })
Example #26
0
def add(request):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    if request.method == "POST":
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image, user=request.user)
        if form.is_valid():
            # Set image file size
            image.file_size = image.file.size

            # Set image file hash
            image.file.seek(0)
            image._set_file_hash(image.file.read())
            image.file.seek(0)

            form.save()

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

            messages.success(
                request,
                _("Image '{0}' added.").format(image.title),
                buttons=[
                    messages.button(
                        reverse("wagtailimages:edit", args=(image.id,)), _("Edit")
                    )
                ],
            )
            return redirect("wagtailimages:index")
        else:
            messages.error(request, _("The image could not be created due to errors."))
    else:
        form = ImageForm(user=request.user)

    return TemplateResponse(
        request,
        "wagtailimages/images/add.html",
        {
            "form": form,
        },
    )
Example #27
0
def edit(request, redirect_id):
    theredirect = get_object_or_404(models.Redirect, id=redirect_id)

    if not permission_policy.user_has_permission_for_instance(
            request.user, "change", theredirect):
        raise PermissionDenied

    if request.method == "POST":
        form = RedirectForm(request.POST, request.FILES, instance=theredirect)
        if form.is_valid():
            with transaction.atomic():
                form.save()
                log(instance=theredirect, action="wagtail.edit")
            messages.success(
                request,
                _("Redirect '{0}' updated.").format(theredirect.title),
                buttons=[
                    messages.button(
                        reverse("wagtailredirects:edit",
                                args=(theredirect.id, )),
                        _("Edit"),
                    )
                ],
            )
            return redirect("wagtailredirects:index")
        else:
            messages.error(request,
                           _("The redirect could not be saved due to errors."))
    else:
        form = RedirectForm(instance=theredirect)

    return TemplateResponse(
        request,
        "wagtailredirects/edit.html",
        {
            "redirect":
            theredirect,
            "form":
            form,
            "user_can_delete":
            permission_policy.user_has_permission(request.user, "delete"),
        },
    )
Example #28
0
def preview_for_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')

    page = revision.as_page_object()

    request.revision_id = revision_id

    # pass in the real user request rather than page.dummy_request(), so that request.user
    # and request.revision_id will be picked up by the wagtail user bar
    return page.serve_preview(request, page.default_preview_mode)
Example #29
0
    def dispatch(self, request, page_id, action_name, task_state_id):
        self.page = get_object_or_404(Page, id=page_id)
        self.action_name = action_name

        self.redirect_to = request.POST.get("next", None)
        if not self.redirect_to or not url_has_allowed_host_and_scheme(
                url=self.redirect_to, allowed_hosts={request.get_host()}):
            self.redirect_to = reverse("wagtailadmin_pages:edit",
                                       args=[page_id])

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

        self.task_state = get_object_or_404(TaskState, id=task_state_id)
        self.task_state = self.task_state.specific

        self.task = self.task_state.task.specific

        actions = self.task.get_actions(self.page, request.user)
        self.action_verbose_name = ""
        action_available = False
        self.action_modal = False

        for name, verbose_name, modal in actions:
            if name == self.action_name:
                action_available = True
                if modal:
                    self.action_modal = True
                    # if two actions have the same name, use the verbose name of the one allowing modal data entry
                    # within the modal
                    self.action_verbose_name = verbose_name
        if not action_available:
            raise PermissionDenied

        self.form_class = self.task.get_form_for_action(self.action_name)

        return super().dispatch(request, page_id, action_name, task_state_id)
Example #30
0
def add(request, media_type):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    if request.POST:
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(request.POST,
                         request.FILES,
                         instance=media,
                         user=request.user)
        if form.is_valid():
            form.save()

            # Reindex the media entry to make sure all tags are indexed
            for backend in get_search_backends():
                backend.add(media)

            messages.success(
                request,
                _("Media file '{0}' added.").format(media.title),
                buttons=[
                    messages.button(
                        reverse("wagtailmedia:edit", args=(media.id, )),
                        _("Edit"))
                ],
            )
            return redirect("wagtailmedia:index")
        else:
            messages.error(
                request, _("The media file could not be saved due to errors."))
    else:
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(user=request.user, instance=media)

    return render(
        request,
        "wagtailmedia/media/add.html",
        {
            "form": form,
            "media_type": media_type,
        },
    )
Example #31
0
def duplicate(request, page):
    if request.method == 'POST':
        form = DuplicateForm(request.POST or None, user=request.user, page=page)
        if form.is_valid():
            try:
                
                export_settings = {'root_page': Page.objects.get(pk=page), 'export_unpublished': False, 
                'export_documents': False, 'export_images': False, 'null_pk': True,
                'null_fk': False, 'null_users': False}

                export_file = exporting.export_page(settings=export_settings)

                overwrite = {
                                'title': form.cleaned_data['new_title'], 
                                'draft_title': form.cleaned_data['new_title'], 
                                'slug': form.cleaned_data['new_slug']
                            }
                
                num_uploaded, num_failed, response = importing.import_page(export_file, form.cleaned_data['new_parent_page'], overwrites = overwrite)

                if not num_failed:
                    messages.success(
                        request,
                        ungettext("%(count)s book duplicated.",
                                "%(count)s books duplicated.", num_uploaded) %
                        {'count': num_uploaded})
                else:
                    messages.success(request, _("%(uploaded)s book(s) were duplicated while %(skipped)s page(s) were skipped because they were already in the environment. %(error)s") % {'uploaded': num_uploaded, 'skipped': num_failed, 'error': response})

                return redirect('wagtailadmin_explore', form.cleaned_data['new_parent_page'].pk)

            except Page.DoesNotExist:
                messages.error(request, _("Duplicate failed because the root book was not found."))        

                return redirect('wagtailadmin_explore', page.pk)
    else:
        form = DuplicateForm(request.POST or None, user=request.user, page=page)

    return render(request, 'duplicatebooks/duplicate.html', {
        'form': form,
        'pageid': page
    })
Example #32
0
    def decorated_view(request, *args, **kwargs):
        user = request.user

        if user.is_anonymous:
            return reject_request(request)

        if user.has_perms(['wagtailadmin.access_admin']):
            if hasattr(user, 'wagtail_userprofile'):
                language = user.wagtail_userprofile.get_preferred_language()
                l18n.set_language(language)
                activate_lang(language)
                time_zone = user.wagtail_userprofile.get_current_time_zone()
                activate_tz(time_zone)
            return view_func(request, *args, **kwargs)

        if not request.is_ajax():
            messages.error(request,
                           _('You do not have permission to access the admin'))

        return reject_request(request)
Example #33
0
def airtable_message(request,
                     instance,
                     message="Airtable record updated",
                     button_text="View record in Airtable",
                     buttons_enabled=True) -> None:
    """
    Common message handler for Wagtail hooks.

    Supports a custom message, custom button text, and the ability to disable buttons entirely (use case: deleting a record)
    """
    if hasattr(instance, "_airtable_update_error"):
        messages.error(request, message=instance._airtable_update_error)
    else:
        buttons = None
        if buttons_enabled and instance.get_record_usage_url():
            buttons = [
                messages.button(instance.get_record_usage_url(), button_text,
                                True)
            ]
        messages.success(request, message=message, buttons=buttons)
Example #34
0
def add_safety_relation(request, usertype, uid, iid):
    edit_handler_cls = get_snippet_edit_handler(SafetyInstructionUserRelation)
    #    print ('Edit handler class is: {}'.format(edit_handler_cls))
    #    print ('Edit handler class is: {}'.format(edit_handler_cls.__dict__))
    #    edit_handler_cls.bind_to(model=SafetyInstructionUserRelation)
    form_cls = edit_handler_cls.get_form_class()  #)
    initials = {'instruction': iid}
    if usertype == 'ruser':
        initials['rubion_user'] = uid
    elif usertype == 'rstaff':
        initials['rubion_staff'] = uid

    instance = SafetyInstructionUserRelation()

    if request.method == 'POST':
        form = form_cls(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            form.save()

            messages.success(request, _('Safety instruction added.'))
            opts = SafetyInstructionUserRelation._meta
            return redirect('/admin/%s/%s/' %
                            (opts.app_label, 'staffusermodelproxy'))

        else:
            messages.error(
                request,
                _("The Safety Instruction could not be created due to errors.")
            )
            edit_handler = edit_handler_cls(instance=instance, form=form)
    else:
        form = form_cls(instance=instance, initial=initials)
        #        edit_handler_cls.bind_to(instance=instance, form=form)
        edit_handler = edit_handler_cls

    return render(
        request, 'userdata/admin/safetyinstruction/create.html', {
            'model_opts': SafetyInstructionUserRelation._meta,
            'edit_handler': edit_handler,
            'form': form,
        })
Example #35
0
def create(request):
    if request.method == 'POST':
        form = get_user_creation_form()(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            messages.success(request,
                             _("User '{0}' created.").format(user),
                             buttons=[
                                 messages.button(
                                     reverse('wagtailusers_users:edit',
                                             args=(user.pk, )), _('Edit'))
                             ])
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request,
                           _("The user could not be created due to errors."))
    else:
        form = get_user_creation_form()()
    return render(request, 'rubauth/users/create.html', {
        'form': form,
    })
Example #36
0
def add(request):
    Document = get_document_model()
    DocumentForm = get_document_form(Document)

    if request.method == 'POST':
        doc = Document(uploaded_by_user=request.user)
        form = DocumentForm(request.POST,
                            request.FILES,
                            instance=doc,
                            user=request.user)
        if form.is_valid():
            doc.file_size = doc.file.size

            # Set new document file hash
            doc.file.seek(0)
            doc._set_file_hash(doc.file.read())
            doc.file.seek(0)

            form.save()

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

            messages.success(request,
                             _("Document '{0}' added.").format(doc.title),
                             buttons=[
                                 messages.button(
                                     reverse('wagtaildocs:edit',
                                             args=(doc.id, )), _('Edit'))
                             ])
            return redirect('wagtaildocs:index')
        else:
            messages.error(request,
                           _("The document could not be saved due to errors."))
    else:
        form = DocumentForm(user=request.user)

    return render(request, "wagtaildocs/documents/add.html", {
        'form': form,
    })
Example #37
0
def import_from_api(request):
    """
    Import a part of a source site's page tree via a direct API request from
    this Wagtail Admin to the source site

    The source site's base url and the source page id of the point in the
    tree to import defined what to import and the destination parent page
    defines where to import it to.
    """
    if request.method == 'POST':
        form = ImportFromAPIForm(request.POST)
        if form.is_valid():
            # remove trailing slash from base url
            base_url = re.sub(r'\/$', '',
                              form.cleaned_data['source_site_base_url'])
            import_url = (base_url +
                          reverse('wagtailimportexport:export',
                                  args=[form.cleaned_data['source_page_id']]))
            r = requests.get(import_url)
            import_data = r.json()
            parent_page = form.cleaned_data['parent_page']

            try:
                page_count = import_pages(import_data, parent_page)
            except LookupError as e:
                messages.error(request,
                               _("Import failed: %(reason)s") % {'reason': e})
            else:
                messages.success(
                    request,
                    ungettext("%(count)s page imported.",
                              "%(count)s pages imported.", page_count) %
                    {'count': page_count})
            return redirect('wagtailadmin_explore', parent_page.pk)
    else:
        form = ImportFromAPIForm()

    return render(request, 'wagtailimportexport/import_from_api.html', {
        'form': form,
    })
Example #38
0
def edit(request, embed_video_id):
    EmbedVideo = get_embed_video_model()
    EmbedVideoForm = get_embed_video_form(EmbedVideo)

    embed_video = get_object_or_404(EmbedVideo, id=embed_video_id)

    if not embed_video.is_editable_by_user(request.user):
        raise PermissionDenied

    if request.POST:
        form = EmbedVideoForm(request.POST,
                              request.FILES,
                              instance=embed_video)
        if form.is_valid():
            form.save()

            # Reindex the embed_video to make sure all tags are indexed
            for backend in get_search_backends():
                backend.add(embed_video)

            messages.success(
                request,
                _("Video '{0}' updated.").format(embed_video.title),
                buttons=[
                    messages.button(
                        reverse('wagtail_embed_videos_edit_embed_video',
                                args=(embed_video.id, )), _('Edit again'))
                ])
            return redirect('wagtail_embed_videos_index')
        else:
            messages.error(request,
                           _("The video could not be saved due to errors."))
    else:
        form = EmbedVideoForm(instance=embed_video)

    return render(request, "wagtail_embed_videos/embed_videos/edit.html", {
        'embed_video': embed_video,
        'form': form,
    })
Example #39
0
def approve_moderation(request, revision_id):
    revision = get_object_or_404(Revision.page_revisions, id=revision_id)
    if not revision.content_object.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.content_object.specific_deferred.get_admin_display_title()
            ),
        )
        return redirect("wagtailadmin_home")

    if request.method == "POST":
        revision.approve_moderation(user=request.user)

        message = _("Page '{0}' published.").format(
            revision.content_object.specific_deferred.get_admin_display_title()
        )
        buttons = []
        if revision.content_object.url is not None:
            buttons.append(
                messages.button(
                    revision.content_object.url, _("View live"), new_window=False
                )
            )
        buttons.append(
            messages.button(
                reverse("wagtailadmin_pages:edit", args=(revision.content_object.id,)),
                _("Edit"),
            )
        )
        messages.success(request, message, buttons=buttons)

        if not send_moderation_notification(revision, "approved", request.user):
            messages.error(request, _("Failed to send approval notifications"))

    return redirect("wagtailadmin_home")
Example #40
0
def edit(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    can_delete = user_can_delete_user(request.user, user)
    editing_self = request.user == user

    for fn in hooks.get_hooks('before_edit_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_edit_form()(request.POST,
                                    request.FILES,
                                    instance=user,
                                    editing_self=editing_self)
        if form.is_valid():
            user = form.save()
            messages.success(request,
                             _("User '{0}' updated.").format(user),
                             buttons=[
                                 messages.button(
                                     reverse('wagtailusers_users:edit',
                                             args=(user.pk, )), _('Edit'))
                             ])
            for fn in hooks.get_hooks('after_edit_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request,
                           _("The user could not be saved due to errors."))
    else:
        form = get_user_edit_form()(instance=user, editing_self=editing_self)

    return render(request, 'wagtailusers/users/edit.html', {
        'user': user,
        'form': form,
        'can_delete': can_delete,
    })
Example #41
0
def move_confirm(request, page_to_move_id, destination_id):
    page_to_move = get_object_or_404(Page, id=page_to_move_id).specific
    destination = get_object_or_404(Page, id=destination_id)
    if not page_to_move.permissions_for_user(request.user).can_move_to(destination):
        raise PermissionDenied

    if not Page._slug_is_available(page_to_move.slug, destination, page=page_to_move):
        messages.error(
            request,
            _("The slug '{0}' is already in use at the selected parent page. Make sure the slug is unique and try again".format(page_to_move.slug))
        )
        return redirect('wagtailadmin_pages:move_choose_destination', page_to_move.id, destination.id)

    for fn in hooks.get_hooks('before_move_page'):
        result = fn(request, page_to_move, destination)
        if hasattr(result, 'status_code'):
            return result

    if request.method == 'POST':
        # any invalid moves *should* be caught by the permission check above,
        # so don't bother to catch InvalidMoveToDescendant
        page_to_move.move(destination, pos='last-child')

        messages.success(request, _("Page '{0}' moved.").format(page_to_move.get_admin_display_title()), buttons=[
            messages.button(reverse('wagtailadmin_pages:edit', args=(page_to_move.id,)), _('Edit'))
        ])

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

        return redirect('wagtailadmin_explore', destination.id)

    return render(request, 'wagtailadmin/pages/confirm_move.html', {
        'page_to_move': page_to_move,
        'destination': destination,
    })
def export_page(request):
    """
    View for the export page.
    """

    if request.method == 'POST':
        form = forms.ExportPage(request.POST)

        if form.is_valid():
            export_file = exporting.export_page(settings=form.cleaned_data)

            if export_file:
                # Grab ZIP file from in-memory, make response with correct MIME-type
                response = HttpResponse(export_file.getvalue(), content_type = "application/x-zip-compressed")
                
                # ..and correct content-disposition
                response['Content-Disposition'] = 'attachment; filename=wagtail-export.zip'

                return response
            else:
                form = forms.ExportPage()

                messages.error(
                    request, "Failed to generate an export file. Please refer to the logs for further details."
                )

                # Redirect client to form.
                return render(request, 'wagtailimportexport/export-page.html', {
                    'form': form,
                })

    else:
        form = forms.ExportPage()

        # Redirect client to form.
        return render(request, 'wagtailimportexport/export-page.html', {
            'form': form,
        })
Example #43
0
def move_confirm(request, page_to_move_id, destination_id):
    page_to_move = get_object_or_404(Page, id=page_to_move_id).specific
    destination = get_object_or_404(Page, id=destination_id)
    if not page_to_move.permissions_for_user(request.user).can_move_to(destination):
        raise PermissionDenied

    if not Page._slug_is_available(page_to_move.slug, destination, page=page_to_move):
        messages.error(
            request,
            _("The slug '{0}' is already in use at the selected parent page. Make sure the slug is unique and try again".format(page_to_move.slug))
        )
        return redirect('wagtailadmin_pages:move_choose_destination', page_to_move.id, destination.id)

    for fn in hooks.get_hooks('before_move_page'):
        result = fn(request, page_to_move, destination)
        if hasattr(result, 'status_code'):
            return result

    if request.method == 'POST':
        # any invalid moves *should* be caught by the permission check above,
        # so don't bother to catch InvalidMoveToDescendant
        page_to_move.move(destination, pos='last-child')

        messages.success(request, _("Page '{0}' moved.").format(page_to_move.get_admin_display_title()), buttons=[
            messages.button(reverse('wagtailadmin_pages:edit', args=(page_to_move.id,)), _('Edit'))
        ])

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

        return redirect('wagtailadmin_explore', destination.id)

    return render(request, 'wagtailadmin/pages/confirm_move.html', {
        'page_to_move': page_to_move,
        'destination': destination,
    })
Example #44
0
def create(request):
    for fn in hooks.get_hooks("before_create_user"):
        result = fn(request)
        if hasattr(result, "status_code"):
            return result
    if request.method == "POST":
        form = get_user_creation_form()(request.POST, request.FILES)
        if form.is_valid():
            with transaction.atomic():
                user = form.save()
                log(user, "wagtail.create")
            messages.success(
                request,
                _("User '{0}' created.").format(user),
                buttons=[
                    messages.button(
                        reverse("wagtailusers_users:edit", args=(user.pk, )),
                        _("Edit"))
                ],
            )
            for fn in hooks.get_hooks("after_create_user"):
                result = fn(request, user)
                if hasattr(result, "status_code"):
                    return result
            return redirect("wagtailusers_users:index")
        else:
            messages.error(request,
                           _("The user could not be created due to errors."))
    else:
        form = get_user_creation_form()()

    return TemplateResponse(
        request,
        "wagtailusers/users/create.html",
        {
            "form": form,
        },
    )
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()

        message = _("Page '{0}' published.").format(revision.page.get_admin_display_title())
        buttons = []
        if revision.page.url is not None:
            buttons.append(messages.button(revision.page.url, _('View live'), new_window=True))
        buttons.append(messages.button(reverse('wagtailadmin_pages:edit', args=(revision.page.id,)), _('Edit')))
        messages.success(request, message, buttons=buttons)

        if not send_notification(revision.id, 'approved', request.user.pk):
            messages.error(request, _("Failed to send approval notifications"))

    return redirect('wagtailadmin_home')
Example #46
0
def preview_for_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.specific_deferred.get_admin_display_title()))
        return redirect('wagtailadmin_home')

    page = revision.as_page_object()

    try:
        preview_mode = page.default_preview_mode
    except IndexError:
        raise PermissionDenied

    return page.make_preview_request(
        request,
        preview_mode,
        extra_request_attrs={'revision_id': revision_id})
Example #47
0
def edit(request, redirect_id):
    theredirect = get_object_or_404(models.Redirect, id=redirect_id)

    if not permission_policy.user_has_permission_for_instance(
            request.user, 'change', theredirect):
        raise PermissionDenied

    if request.method == 'POST':
        form = RedirectForm(request.POST, request.FILES, instance=theredirect)
        if form.is_valid():
            with transaction.atomic():
                form.save()
                log(instance=theredirect, action='wagtail.edit')
            messages.success(
                request,
                _("Redirect '{0}' updated.").format(theredirect.title),
                buttons=[
                    messages.button(
                        reverse('wagtailredirects:edit',
                                args=(theredirect.id, )), _('Edit'))
                ])
            return redirect('wagtailredirects:index')
        else:
            messages.error(request,
                           _("The redirect could not be saved due to errors."))
    else:
        form = RedirectForm(instance=theredirect)

    return TemplateResponse(
        request, "wagtailredirects/edit.html", {
            'redirect':
            theredirect,
            'form':
            form,
            'user_can_delete':
            permission_policy.user_has_permission(request.user, 'delete'),
        })
Example #48
0
def index(request):

    form = SearchForm(placeholder=_("Search something"))

    example_form = ExampleForm()

    messages.success(request,
                     _("Success message"),
                     buttons=[
                         messages.button('', _('View live')),
                         messages.button('', _('Edit'))
                     ])
    messages.warning(request,
                     _("Warning message"),
                     buttons=[
                         messages.button('', _('View live')),
                         messages.button('', _('Edit'))
                     ])
    messages.error(request,
                   _("Error message"),
                   buttons=[
                       messages.button('', _('View live')),
                       messages.button('', _('Edit'))
                   ])

    paginator = Paginator(list(range(100)), 10)
    page = paginator.page(2)

    user = User(email='*****@*****.**')

    return render(
        request, 'wagtailstyleguide/base.html', {
            'search_form': form,
            'example_form': example_form,
            'example_page': page,
            'user': user,
        })
Example #49
0
def add(request):
    Video = get_video_model()
    VideoForm = get_video_form(Video)

    if request.POST:
        video = Video(uploaded_by_user=request.user)
        form = VideoForm(request.POST,
                         request.FILES,
                         instance=video,
                         user=request.user)
        if form.is_valid():
            # Save
            video = form.save(commit=False)
            video.file_size = video.file.size
            video.save()

            # Success! Send back an edit form
            for backend in get_search_backends():
                backend.add(video)

            messages.success(request,
                             _("Video '{0}' added.").format(video.title),
                             buttons=[
                                 messages.button(
                                     reverse('wagtailvideos:edit',
                                             args=(video.id, )), _('Edit'))
                             ])
            return redirect('wagtailvideos:index')
        else:
            messages.error(request,
                           _("The video could not be created due to errors."))
    else:
        form = VideoForm(user=request.user)

    return render(request, "wagtailvideos/videos/add.html", {
        'form': form,
    })
Example #50
0
def preview_revision_for_task(request, page_id, task_id):
    """Preview the revision linked to the in-progress TaskState of a specified Task. This enables pages in moderation
    to be edited and new TaskStates linked to the new revisions created, with preview links remaining valid"""

    page = get_object_or_404(Page, id=page_id)
    task = get_object_or_404(Task, id=task_id).specific
    try:
        task_state = TaskState.objects.get(page_revision__page=page, task=task, status=TaskState.STATUS_IN_PROGRESS)
    except TaskState.DoesNotExist:
        messages.error(request, _("The page '{0}' is not currently awaiting moderation in task '{1}'.").format(page.get_admin_display_title(), task.name))
        return redirect('wagtailadmin_home')

    revision = task_state.page_revision

    if not task.get_actions(page, request.user):
        raise PermissionDenied

    page_to_view = revision.as_page_object()

    # TODO: provide workflow actions within this view

    return page_to_view.make_preview_request(request, page.default_preview_mode, extra_request_attrs={
        'revision_id': revision.id
    })
Example #51
0
def add(request):
    if request.method == 'POST':
        form = RedirectForm(request.POST, request.FILES)
        if form.is_valid():
            theredirect = form.save()

            messages.success(
                request,
                _("Redirect '{0}' added.").format(theredirect.title),
                buttons=[
                    messages.button(
                        reverse('wagtailredirects:edit',
                                args=(theredirect.id, )), _('Edit'))
                ])
            return redirect('wagtailredirects:index')
        else:
            messages.error(
                request, _("The redirect could not be created due to errors."))
    else:
        form = RedirectForm()

    return render(request, "wagtailredirects/add.html", {
        'form': form,
    })
Example #52
0
def add(request):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    if request.method == 'POST':
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST,
                         request.FILES,
                         instance=image,
                         user=request.user)
        if form.is_valid():
            # Set image file size
            image.file_size = image.file.size

            form.save()

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

            messages.success(request,
                             _("Image '{0}' added.").format(image.title),
                             buttons=[
                                 messages.button(
                                     reverse('wagtailimages:edit',
                                             args=(image.id, )), _('Edit'))
                             ])
            return redirect('wagtailimages:index')
        else:
            messages.error(request,
                           _("The image could not be created due to errors."))
    else:
        form = ImageForm(user=request.user)

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
    })
Example #53
0
def edit_profile(request):
    if request.user.is_authenticated:
        if request.user.has_perm('wagtailadmin.access_admin'):
            return redirect('wagtailusers_users:edit')
        if request.method == 'POST':
            form = EditProfilePage(request.POST)
            if form.is_valid():
                user = request.user
                for field in form.changed_data:
                    # if field == 'subunions':
                    #     user.subunions.clear()
                    #     for subunion in form.cleaned_data.get('subunions'):
                    #         user.subunions.add(subunion)
                    # else:
                    setattr(user, field, form.cleaned_data.get(field))
                user.save()
                messages.success(request, "Profile updated successfully.")
                return redirect(reverse_lazy('members:account_home'))
        else:
            form = EditProfilePage()
        return render(request, 'account_profile_update.html', {'form': form})
    else:
        messages.error(request, "Please login to your account.")
        return redirect(reverse_lazy('members:signin'))
Example #54
0
def edit(request, query_id):
    query = get_object_or_404(Query, id=query_id)

    if request.method == 'POST':
        # Get query
        query_form = search_forms.QueryForm(request.POST)
        # and the recommendations
        searchpicks_formset = forms.SearchPromotionsFormSet(request.POST, instance=query)

        if query_form.is_valid():
            new_query = Query.get(query_form['query_string'].value())

            # Save search picks
            if save_searchpicks(query, new_query, searchpicks_formset):
                messages.success(request, _("Editor's picks for '{0}' updated.").format(new_query), buttons=[
                    messages.button(reverse('wagtailsearchpromotions:edit', args=(query.id,)), _('Edit'))
                ])
                return redirect('wagtailsearchpromotions:index')
            else:
                if len(searchpicks_formset.non_form_errors()):
                    messages.error(request, " ".join(error for error in searchpicks_formset.non_form_errors()))
                    # formset level error (e.g. no forms submitted)
                else:
                    messages.error(request, _("Recommendations have not been saved due to errors"))
                    # specific errors will be displayed within form fields

    else:
        query_form = search_forms.QueryForm(initial=dict(query_string=query.query_string))
        searchpicks_formset = forms.SearchPromotionsFormSet(instance=query)

    return render(request, 'wagtailsearchpromotions/edit.html', {
        'query_form': query_form,
        'searchpicks_formset': searchpicks_formset,
        'query': query,
        'form_media': query_form.media + searchpicks_formset.media,
    })
Example #55
0
def edit(request, image_id):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    image = get_object_or_404(Image, id=image_id)

    if not permission_policy.user_has_permission_for_instance(request.user, 'change', image):
        return permission_denied(request)

    if request.method == 'POST':
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image, user=request.user)
        if form.is_valid():
            if 'file' in form.changed_data:
                # Set new image file size
                image.file_size = image.file.size

            form.save()

            if 'file' in form.changed_data:
                # if providing a new image file, delete the old one and all renditions.
                # NB Doing this via original_file.delete() clears the file field,
                # which definitely isn't what we want...
                original_file.storage.delete(original_file.name)
                image.renditions.all().delete()

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

            messages.success(request, _("Image '{0}' updated.").format(image.title), buttons=[
                messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit again'))
            ])
            return redirect('wagtailimages:index')
        else:
            messages.error(request, _("The image could not be saved due to errors."))
    else:
        form = ImageForm(instance=image, user=request.user)

    # Check if we should enable the frontend url generator
    try:
        reverse('wagtailimages_serve', args=('foo', '1', 'bar'))
        url_generator_enabled = True
    except NoReverseMatch:
        url_generator_enabled = False

    if image.is_stored_locally():
        # Give error if image file doesn't exist
        if not os.path.isfile(image.file.path):
            messages.error(request, _(
                "The source image file could not be found. Please change the source or delete the image."
            ).format(image.title), buttons=[
                messages.button(reverse('wagtailimages:delete', args=(image.id,)), _('Delete'))
            ])

    return render(request, "wagtailimages/images/edit.html", {
        'image': image,
        'form': form,
        'url_generator_enabled': url_generator_enabled,
        'filesize': image.get_file_size(),
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', image
        ),
    })
Example #56
0
 def form_invalid(self, form):
     self.form = form
     error_message = self.get_error_message()
     if error_message is not None:
         messages.error(self.request, error_message)
     return super().form_invalid(form)
Example #57
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 = page_class.get_edit_handler()
    form_class = edit_handler.get_form_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:
                    buttons = []
                    if page.url is not None:
                        buttons.append(messages.button(page.url, _('View live'), new_window=True))
                    buttons.append(messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit')))
                    messages.success(request, _("Page '{0}' created and published.").format(page.get_admin_display_title()), buttons=buttons)
            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.bind_to_instance(instance=page,
                                                         form=form,
                                                         request=request)
            has_unsaved_changes = True
    else:
        signals.init_new_page.send(sender=create, page=page, parent=parent_page)
        form = form_class(instance=page, parent_page=parent_page)
        edit_handler = edit_handler.bind_to_instance(instance=page, form=form, request=request)
        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,
    })
Example #58
0
def edit(request, page_id):
    real_page_record = get_object_or_404(Page, id=page_id)
    latest_revision = real_page_record.get_latest_revision()
    page = real_page_record.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 = page_class.get_edit_handler()
    form_class = edit_handler.get_form_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,
            )
            # store submitted go_live_at for messaging below
            go_live_at = page.go_live_at

            # 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 go_live_at and 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:
                        if page.live:
                            message = _(
                                "Page '{0}' is live and this revision has been scheduled for publishing."
                            ).format(
                                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()
                        )

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

            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.bind_to_instance(instance=page,
                                                         form=form,
                                                         request=request)
            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, parent_page=parent)
        edit_handler = edit_handler.bind_to_instance(instance=page, form=form, request=request)
        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)

    if page.live and page.has_unpublished_changes:
        # Page status needs to present the version of the page containing the correct live URL
        page_for_status = real_page_record.specific
    else:
        page_for_status = page

    return render(request, 'wagtailadmin/pages/edit.html', {
        'page': page,
        'page_for_status': page_for_status,
        '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,
    })
Example #59
0
 def form_invalid(self, form):
     messages.error(self.request, self.get_error_message())
     return self.render_to_response(self.get_context_data())