def add(request):
    EmbedVideoModel = get_embed_video_model()
    EmbedVideoForm = get_embed_video_form(EmbedVideoModel)

    if request.method == 'POST':
        embed_video = EmbedVideoModel(uploaded_by_user=request.user)
        form = EmbedVideoForm(request.POST, request.FILES, instance=embed_video, user=request.user)
        if form.is_valid():
            form.save()

            # Reindex the embed video to make sure all tags are indexed
            search_index.insert_or_update_object(embed_video)

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

    return render(request, "wagtail_embed_videos/embed_videos/add.html", {
        'form': form,
    })
Esempio n. 2
0
def edit(request, report_id):
    ReportPanel = get_report_panel_model()
    ReportPanelForm = get_report_panel_form(ReportPanel)

    report_panel = get_object_or_404(ReportPanel, id=report_id)

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

    if request.method == 'POST':
        form = ReportPanelForm(request.POST, request.FILES, instance=report_panel) # user=request.user
        if form.is_valid():
            report = form.save()

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

            messages.success(request, _("ReportPanel '{0}' updated").format(report.title), buttons=[
                messages.button(reverse('wagtailreportpanels:edit', args=(report.id,)), _('Edit'))
            ])
            return redirect('wagtailreportpanels:index')
        else:
            messages.error(request, _("The report panel could not be saved due to errors."))
    else:
        form = ReportPanelForm(instance=report_panel)  # TODO: user=request.user

    return render(request, "wagtailreports/report_panels/edit.html", {
        'report_panel': report_panel,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', report_panel
        ),
    })
Esempio n. 3
0
    def test_doesnt_insert_unsaved_object(self, backend):
        obj = models.SearchTest(title="Test")
        backend().reset_mock()

        index.insert_or_update_object(obj)

        self.assertFalse(backend().add.mock_calls)
Esempio n. 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,
    })
Esempio n. 5
0
def chooser_upload(request):
    Document = get_document_model()
    DocumentForm = get_document_form(Document)

    if request.method == 'POST':
        document = Document(uploaded_by_user=request.user)
        form = DocumentForm(request.POST, request.FILES, instance=document, user=request.user)

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

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

            return render_modal_workflow(
                request, None, 'wagtaildocs/chooser/document_chosen.js',
                {'document_json': get_document_json(document)}
            )
    else:
        form = DocumentForm(user=request.user)

    documents = Document.objects.order_by('title')

    return render_modal_workflow(
        request, 'wagtaildocs/chooser/chooser.html', 'wagtaildocs/chooser/chooser.js',
        {'documents': documents, 'uploadform': form}
    )
Esempio n. 6
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():
            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,
    })
Esempio n. 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():
            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,
    })
Esempio n. 8
0
def add(request):
    Report = get_report_model()
    ReportForm = get_report_form(Report)

    if request.method == 'POST':
        report = Report()
        form = ReportForm(request.POST, instance=report)  #user=request.user
        if form.is_valid():
            form.save()

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

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

    return render(request, "wagtailreports/reports/add.html", {
        'form': form,
    })
Esempio n. 9
0
def chooser_upload(request):
    Report = get_report_model()
    ReportForm = get_report_form(Report)

    if request.method == 'POST':
        report = Report(created_by_user=request.user)
        form = ReportForm(request.POST,
                          request.FILES,
                          instance=report,
                          user=request.user)

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

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

            return render_modal_workflow(
                request, None, 'wagtailreports/chooser/report_chosen.js',
                {'report_json': get_report_json(report)})
    else:
        form = ReportForm(user=request.user)

    reports = Report.objects.order_by('title')

    return render_modal_workflow(request,
                                 'wagtailreports/chooser/chooser.html',
                                 'wagtailreports/chooser/chooser.js', {
                                     'reports': reports,
                                     'uploadform': form
                                 })
Esempio n. 10
0
def chooser_upload(request):
    VideoForm = get_video_form(Video)

    searchform = SearchForm()

    if request.POST:
        video = Video(uploaded_by_user=request.user)
        form = VideoForm(request.POST, request.FILES, instance=video)

        if form.is_valid():
            video.uploaded_by_user = request.user
            video.save()

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

            return render_modal_workflow(
                request, None, 'wagtailvideos/chooser/video_chosen.js',
                {'video_json': get_video_json(video)})
    else:
        form = VideoForm()

    videos = Video.objects.order_by('title')
    paginator, videos = paginate(request, videos, per_page=12)

    return render_modal_workflow(request, 'wagtailvideos/chooser/chooser.html',
                                 'wagtailvideos/chooser/chooser.js', {
                                     'videos': videos,
                                     'uploadform': form,
                                     'searchform': searchform
                                 })
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,
    })
Esempio n. 12
0
    def test_inserts_object(self, backend):
        obj = models.SearchTest.objects.create(title="Test")
        backend().reset_mock()

        index.insert_or_update_object(obj)

        backend().add.assert_called_with(obj)
Esempio n. 13
0
def create_image(file_name, user, folder):
    """Creates an image object."""

    image_file = File(
        open(os.path.join(folder.get_complete_path(), file_name), 'rb'))

    # Build a form for validation
    form = ImageForm(
        {
            'title': os.path.splitext(file_name)[0],
            'collection': '1',  # Hard coding the root collection as default
        },
        {'file': image_file},
        user=user)

    if form.is_valid():
        # Save it
        image = form.save(commit=False)
        image.uploaded_by_user = user
        image.file_size = image.file.size
        image.folder = folder
        image.save()

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

        return image
    return None
Esempio n. 14
0
def post_save_signal_handler(instance, update_fields=None, **kwargs):
    if update_fields is not None:
        # fetch a fresh copy of instance from the database to ensure
        # that we're not indexing any of the unsaved data contained in
        # the fields that were not passed in update_fields
        instance = type(instance).objects.get(pk=instance.pk)

    index.insert_or_update_object(instance)
Esempio n. 15
0
    def test_inserts_object(self, backend):
        obj = models.Book.objects.create(title="Test",
                                         publication_date=date(2017, 10, 18),
                                         number_of_pages=100)
        backend().reset_mock()

        index.insert_or_update_object(obj)

        backend().add.assert_called_with(obj)
Esempio n. 16
0
    def test_doesnt_insert_unsaved_object(self, backend):
        obj = models.Book(title="Test",
                          publication_date=date(2017, 10, 18),
                          number_of_pages=100)
        backend().reset_mock()

        index.insert_or_update_object(obj)

        self.assertFalse(backend().add.mock_calls)
Esempio n. 17
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:
                # 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)

    filesize = None

    # Get file size when there is a file associated with the Document object
    if doc.file:
        try:
            filesize = doc.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 document"),
            buttons=[messages.button(reverse('wagtaildocs:delete', args=(doc.id,)), _('Delete'))]
        )

    return render(request, "wagtaildocs/documents/edit.html", {
        'document': doc,
        'filesize': filesize,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', doc
        ),
    })
Esempio n. 18
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():
            if 'file' in form.changed_data:
                # 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)
            doc = form.save()

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

    filesize = None

    # Get file size when there is a file associated with the Document object
    if doc.file:
        try:
            filesize = doc.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 document"),
            buttons=[messages.button(reverse('wagtaildocs:delete', args=(doc.id,)), _('Delete'))]
        )

    return render(request, "wagtaildocs/documents/edit.html", {
        'document': doc,
        'filesize': filesize,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', doc
        ),
    })
Esempio n. 19
0
def add(request):
    response = dict()

    if not permission_policy.user_has_permission(request.user, 'change'):
        response['message'] = "User does not have permission"
        return JsonResponse(response, status=403)

    file = request.FILES.get('files[]')
    title = os.path.splitext(file.name)[0]

    if not title or not file:
        response['message'] = "Title or file missing"
        return JsonResponse(response, status=400)

    extension = os.path.splitext(file.name)[1]
    extension = extension[1:]   # Remove the '.' from the extension

    if extension not in ALLOWED_EXTENSIONS:
        response['message'] = "Invalid file type"
        return JsonResponse(response, status=400)

    folder = None
    folder_id = request.POST.get('folder_id')
    if folder_id and int(folder_id) != -1:
        try:
            folder = ImageFolder.objects.get(id=folder_id)
        except ObjectDoesNotExist:
            response['message'] = "Invalid Folder ID"
            return JsonResponse(response, status=404)

    # Build a form for validation
    form = ImageForm({
        'title': title,
        'collection': '1',  # Hard coding the root collection as default
    }, {
        'file': file
    }, user=request.user)

    if form.is_valid():
        # Save it
        image = form.save(commit=False)
        image.uploaded_by_user = request.user
        image.file_size = image.file.size
        image.folder = folder
        image.save()

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

        response['data'] = get_image_dict(image)
        response['message'] = "Success"
    else:
        response['message'] = "Error creating image"
        # ToDo send a valid respone based on the error
        response['data'] = None
    return JsonResponse(response)
Esempio n. 20
0
    def test_converts_to_specific_page(self, backend):
        root_page = Page.objects.get(id=1)
        page = root_page.add_child(instance=SimplePage(title="test", slug="test", content="test"))

        # Convert page into a generic "Page" object and add it into the index
        unspecific_page = page.page_ptr
        index.insert_or_update_object(unspecific_page)

        # It should be automatically converted back to the specific version
        backend().add.assert_called_with(page)
Esempio n. 21
0
    def test_converts_to_specific_page(self, backend):
        root_page = Page.objects.get(id=1)
        page = root_page.add_child(
            instance=SimplePage(title="test", slug="test", content="test"))

        # Convert page into a generic "Page" object and add it into the index
        unspecific_page = page.page_ptr
        index.insert_or_update_object(unspecific_page)

        # It should be automatically converted back to the specific version
        backend().add.assert_called_with(page)
Esempio n. 22
0
    def test_catches_index_error(self, backend):
        obj = models.SearchTest.objects.create(title="Test")

        backend().add.side_effect = ValueError("Test")

        with self.assertLogs('wagtail.search.index', level='ERROR') as cm:
            index.insert_or_update_object(obj)

        self.assertEqual(len(cm.output), 1)
        self.assertIn("Exception raised while adding <SearchTest: Test> into the 'default' search backend", cm.output[0])
        self.assertIn("Traceback (most recent call last):", cm.output[0])
        self.assertIn("ValueError: Test", cm.output[0])
Esempio n. 23
0
    def test_catches_index_error(self, backend):
        obj = models.SearchTest.objects.create(title="Test")

        backend().add.side_effect = ValueError("Test")

        with self.assertLogs('wagtail.search.index', level='ERROR') as cm:
            index.insert_or_update_object(obj)

        self.assertEqual(len(cm.output), 1)
        self.assertIn(
            "Exception raised while adding <SearchTest: Test> into the 'default' search backend",
            cm.output[0])
        self.assertIn("Traceback (most recent call last):", cm.output[0])
        self.assertIn("ValueError: Test", cm.output[0])
Esempio n. 24
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

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

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

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

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

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

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

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

    context = get_chooser_context(request)
    context.update({
        'images': images,
        'uploadform': form,
    })
    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html',
                                 'wagtailimages/chooser/chooser.js', context)
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 permission_policy.user_has_permission_for_instance(
            request.user, 'change', embed_video):
        return permission_denied(request)

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

            # Reindex the embed video to make sure all tags are indexed
            search_index.insert_or_update_object(embed_video)

            messages.success(request,
                             _("Video '{0}' updated.").format(
                                 embed_video.title),
                             buttons=[
                                 messages.button(
                                     reverse('wagtail_embed_videos:edit',
                                             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, user=request.user)

    return render(
        request, "wagtail_embed_videos/embed_videos/edit.html", {
            'embed_video':
            embed_video,
            'form':
            form,
            'user_can_delete':
            permission_policy.user_has_permission_for_instance(
                request.user, 'delete', embed_video),
        })
Esempio n. 26
0
    def test_catches_index_error(self, backend):
        obj = models.Book.objects.create(title="Test",
                                         publication_date=date(2017, 10, 18),
                                         number_of_pages=100)

        backend().add.side_effect = ValueError("Test")
        backend().reset_mock()

        with self.assertLogs('wagtail.search.index', level='ERROR') as cm:
            index.insert_or_update_object(obj)

        self.assertEqual(len(cm.output), 1)
        self.assertIn(
            "Exception raised while adding <Book: Test> into the 'default' search backend",
            cm.output[0])
        self.assertIn("Traceback (most recent call last):", cm.output[0])
        self.assertIn("ValueError: Test", cm.output[0])
Esempio n. 27
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    searchform = SearchForm()

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

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

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

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

    images = Image.objects.order_by('title')

    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html',
                                 'wagtailimages/chooser/chooser.js', {
                                     'images': images,
                                     'uploadform': form,
                                     'searchform': searchform
                                 })
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 permission_policy.user_has_permission_for_instance(request.user, 'change', embed_video):
        return permission_denied(request)

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

            # Reindex the embed video to make sure all tags are indexed
            search_index.insert_or_update_object(embed_video)

            messages.success(
                request,
                _("Video '{0}' updated.").format(embed_video.title), buttons=[
                    messages.button(
                        reverse(
                            'wagtail_embed_videos:edit',
                            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, user=request.user)

    return render(request, "wagtail_embed_videos/embed_videos/edit.html", {
        'embed_video': embed_video,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', embed_video
        ),
    })
Esempio n. 29
0
def chooser_upload(request):
    EmbedVideo = get_embed_video_model()
    EmbedVideoForm = get_embed_video_form(EmbedVideo)

    searchform = SearchForm()

    if request.POST:
        embed_video = EmbedVideo(uploaded_by_user=request.user)
        form = EmbedVideoForm(request.POST, request.FILES, instance=embed_video, user=request.user)

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

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

            # TODO: Why use embed video format?
            """
            if request.GET.get('select_format'):
                form = EmbedVideoInsertionForm(initial={'alt_text': embed_video.default_alt_text})
                return render_modal_workflow(
                    request, 'wagtail_embed_videos/chooser/select_format.html',
                    'wagtail_embed_videos/chooser/select_format.js',
                    {'embed_video': embed_video, 'form': form}
                )
            else:
            """
            # not specifying a format; return the embed video details now
            return render_modal_workflow(
                request, None, 'wagtail_embed_videos/chooser/embed_video_chosen.js',
                {'embed_video_json': get_embed_video_json(embed_video)}
            )
    else:
        form = EmbedVideoForm(user=request.user)

    embed_videos = EmbedVideo.objects.order_by('-created_at')
    paginator, images = paginate(request, embed_videos, per_page=12)

    return render_modal_workflow(
        request, 'wagtail_embed_videos/chooser/chooser.html', 'wagtail_embed_videos/chooser/chooser.js',
        {'embed_videos': embed_videos, 'uploadform': form, 'searchform': searchform}
    )
Esempio n. 30
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    searchform = SearchForm()

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

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

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

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

    images = Image.objects.order_by('-created_at')
    paginator, images = paginate(request, images, per_page=12)

    return render_modal_workflow(
        request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js',
        {'images': images, 'uploadform': form, 'searchform': searchform}
    )
Esempio n. 31
0
def edit(request, image_id):
    response = dict()

    if not permission_policy.user_has_permission(request.user, 'change'):
        response['message'] = "User does not have permission"
        return JsonResponse(response, status=403)

    try:
        image = Image.objects.get(id=image_id)
    except ObjectDoesNotExist:
        response['message'] = "Invalid ID"
        return JsonResponse(response, status=404)

    title = request.POST.get('title')
    if title:
        image.title = title
        image.save()
        search_index.insert_or_update_object(image)
        response['message'] = "Success"
        response['data'] = get_image_dict(image)
        return JsonResponse(response)
    else:
        response['message'] = "Title not passed"
        return JsonResponse(response, status=400)
Esempio n. 32
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:
                # 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()

                # Set new 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}' 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
        ),
    })
Esempio n. 33
0
    def test_inserts_object(self, backend):
        obj = models.SearchTest.objects.create(title="Test")
        index.insert_or_update_object(obj)

        backend().add.assert_called_with(obj)
Esempio n. 34
0
    def test_doesnt_insert_unsaved_object(self, backend):
        obj = models.SearchTest(title="Test")
        index.insert_or_update_object(obj)

        self.assertFalse(backend().add.mock_calls)
def post_save_signal_handler(instance, **kwargs):
    index.insert_or_update_object(instance)
Esempio n. 36
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:
                # 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()

                # Set new 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}' 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),
        })
Esempio n. 37
0
def move(request):
    response = dict()
    if not permission_policy.user_has_permission(request.user, 'change'):
        response['message'] = "User does not have permission"
        return JsonResponse(response, status=403)

    source_id = request.POST.get('source_id')
    target_id = request.POST.get('target_id')
    source_type = request.POST.get('source_type')
    count = 0  # Indicates number of attempts to rename a file/folder

    if not source_id or not target_id or not source_type:
        response['message'] = "Image or folder ID missing"
        return JsonResponse(response, status=400)

    if int(target_id) == -1:
        target_folder = None  # Root folder
        target_absolute_path = os.path.join(settings.MEDIA_ROOT,
                                            IMAGES_FOLDER_NAME)
        target_relative_path = IMAGES_FOLDER_NAME
    else:
        try:
            target_folder = ImageFolder.objects.get(id=target_id)
        except ObjectDoesNotExist:
            response['message'] = "Invalid target ID"
            return JsonResponse(response, status=404)
        else:
            target_absolute_path = target_folder.get_complete_path()
            target_relative_path = target_folder.path

    if source_type == 'image':
        try:
            image = Image.objects.get(id=source_id)
        except ObjectDoesNotExist:
            response['message'] = "Invalid source ID"
            return JsonResponse(response, status=404)

        image.folder = target_folder  # Change the folder

        # Move the file to the updated location
        # When moving a file to a new location, check if a file
        # with the same name exists.
        # If yes, then append a number to the filename and save
        initial_path = image.file.path
        complete_file_name = image.filename
        file_name = os.path.splitext(image.filename)[0]  # get the filename
        extension = os.path.splitext(image.filename)[1]  # get the extension
        new_path = os.path.join(target_absolute_path, complete_file_name)
        while True:
            # Keeping renaming until there are no more filename clashes
            if os.path.exists(new_path):
                count += 1
                complete_file_name = file_name + str(count) + extension
                new_path = os.path.join(target_absolute_path,
                                        complete_file_name)
            else:
                os.rename(initial_path, new_path)
                if count:
                    # If there were attempts made to resolve conflict,
                    # change the image's title
                    # Append the count to the title
                    image.title = image.title + str(count)
                    response[
                        'message'] = "File with the same name exists! Renaming to avoid conflict."
                else:
                    response['message'] = "Success"
                break

        image.file.name = os.path.join(target_relative_path,
                                       complete_file_name)
        image.save()
        search_index.insert_or_update_object(image)
        response['data'] = get_image_dict(image)

    elif source_type == 'folder':

        if source_id == target_id:
            response[
                'message'] = "Source and target forlder ID cannot be the same."
            return JsonResponse(response, status=400)

        try:
            source_folder = ImageFolder.objects.get(id=source_id)
        except ObjectDoesNotExist:
            response['message'] = "Invalid Folder ID"
            return JsonResponse(response, status=404)

        source_folder.folder = target_folder
        while True:
            try:
                # Check if the folder is present in the DB or physically present in the OS
                source_folder.validate_folder()
            except ValidationError as e:
                count += 1
                if e.code == 'db':
                    source_folder.title = source_folder.title + str(count)
                else:
                    # When a folder with a clashing name exists in the OS,
                    # Add the entry to the DB and notify the user.
                    # Abort the current move operation
                    new_folder = create_db_entries(source_folder.title,
                                                   request.user, target_folder)
                    folders_list = get_folders_list([new_folder])
                    response[
                        'message'] = "Operation Failed! Found new entry in the OS. Loading the folder..."
                    response['data'] = folders_list[0]
                    # Return a 202 as the intended action was not completed
                    return JsonResponse(response, status=202)
            else:
                if count:
                    # If there were attempts made to resolve conflict
                    response[
                        'message'] = "Folder with the same name exists! Renaming to avoid conflict."
                else:
                    response['message'] = "Success"
                break
        source_folder.save()
        response['data'] = get_folders_list([source_folder])[0]
    else:
        response['message'] = "Invalid source type"
        return JsonResponse(response, status=400)
    return JsonResponse(response)