Пример #1
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 image.is_editable_by_user(request.user):
        raise PermissionDenied

    if request.POST:
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image)
        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
            for backend in get_search_backends():
                backend.add(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)

    # 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(),
    })
Пример #2
0
def add(request):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    if request.POST:
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image)
        if form.is_valid():
            form.save()

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

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

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
        'max_filesize': MAX_UPLOAD_SIZE,
    })
Пример #3
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})
Пример #4
0
    def test_custom_image_model_without_admin_form_fields_raises_warning(self):
        self.reset_warning_registry()
        with warnings.catch_warnings(record=True) as w:
            form = get_image_form(CustomImageWithoutAdminFormFields)

            # Check that a RemovedInWagtail12Warning has been triggered
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[-1].category, RemovedInWagtail12Warning))
            self.assertTrue(
                "Add admin_form_fields = (tuple of field names) to CustomImageWithoutAdminFormFields"
                in str(w[-1].message)
            )

        # All fields, including the not editable one should be on the form
        self.assertEqual(
            list(form.base_fields.keys()),
            [
                "title",
                "file",
                "focal_point_x",
                "focal_point_y",
                "focal_point_width",
                "focal_point_height",
                "caption",
                "not_editable_field",
                "tags",
            ],
        )
Пример #5
0
    def test_custom_image_model_without_admin_form_fields_raises_warning(self):
        self.reset_warning_registry()
        with warnings.catch_warnings(record=True) as w:
            form = get_image_form(CustomImageWithoutAdminFormFields)

            # Check that a RemovedInWagtail12Warning has been triggered
            self.assertEqual(len(w), 1)
            self.assertTrue(
                issubclass(w[-1].category, RemovedInWagtail12Warning))
            self.assertTrue(
                "Add admin_form_fields = (tuple of field names) to CustomImageWithoutAdminFormFields"
                in str(w[-1].message))

        # All fields, including the not editable one should be on the form
        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
            'caption',
            'not_editable_field',
            'tags',
        ])
Пример #6
0
    def test_custom_image_model_without_admin_form_fields_raises_warning(self):
        self.reset_warning_registry()
        with warnings.catch_warnings(record=True) as raw_warnings:
            form = get_image_form(CustomImageWithoutAdminFormFields)

            # Check that a RemovedInWagtail12Warning has been triggered

            # Ignore any ResourceWarnings. TODO: remove this when we've stopped ResourceWarnings from happening...
            try:
                clean_warnings = [w for w in raw_warnings if not issubclass(w.category, ResourceWarning)]
            except NameError:  # ResourceWarning only exists on Python >= 3.2
                clean_warnings = raw_warnings

            self.assertEqual(len(clean_warnings), 1)
            self.assertTrue(issubclass(clean_warnings[-1].category, RemovedInWagtail12Warning))
            self.assertTrue("Add admin_form_fields = (tuple of field names) to CustomImageWithoutAdminFormFields" in str(clean_warnings[-1].message))

        # All fields, including the not editable one should be on the form
        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
            'caption',
            'not_editable_field',
            'tags',
        ])
Пример #7
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form()

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

        if form.is_valid():
            form.save()
            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()

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

    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html',
                                 'wagtailimages/chooser/chooser.js', {
                                     'images': images,
                                     'uploadform': form
                                 })
Пример #8
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form()

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

        if form.is_valid():
            form.save()
            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()

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

    return render_modal_workflow(
        request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js',
        {'images': images, 'uploadform': form}
    )
Пример #9
0
def edit(request, image_id):
    Image = get_image_model()
    ImageForm = get_image_form()

    image = get_object_or_404(Image, id=image_id)

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

    if request.POST:
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image)
        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()
            form.save()
            messages.success(request, _("Image '{0}' updated.").format(image.title))
            return redirect("wagtailimages_index")
        else:
            messages.error(request, _("The image could not be saved due to errors."))
    else:
        form = ImageForm(instance=image)

    return render(request, "wagtailimages/images/edit.html", {"image": image, "form": form})
Пример #10
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,
    })
Пример #11
0
def edit(request, image_id):
    Image = get_image_model()
    ImageForm = get_image_form()

    image = get_object_or_404(Image, id=image_id)

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

    if request.POST:
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image)
        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()
            form.save()
            messages.success(request,
                             _("Image '{0}' updated.").format(image.title))
            return redirect('wagtailimages_index')
        else:
            messages.error(request,
                           _("The image could not be saved due to errors."))
    else:
        form = ImageForm(instance=image)

    return render(request, "wagtailimages/images/edit.html", {
        'image': image,
        'form': form,
    })
Пример #12
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form()

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

        if form.is_valid():
            form.save()
            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()

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

    return render_modal_workflow(
        request,
        "wagtailimages/chooser/chooser.html",
        "wagtailimages/chooser/chooser.js",
        {"images": images, "uploadform": form},
    )
Пример #13
0
    def test_fields(self):
        form = get_image_form(Image)

        self.assertEqual(
            list(form.base_fields.keys()),
            ["title", "file", "tags", "focal_point_x", "focal_point_y", "focal_point_width", "focal_point_height"],
        )
Пример #14
0
def add(request):
    ImageForm = get_image_form()
    ImageModel = get_image_model()

    if request.POST:
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image)
        if form.is_valid():
            form.save()

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

            messages.success(request, _("Image '{0}' added.").format(image.title))
            return redirect('wagtailimages_index')
        else:
            messages.error(request, _("The image could not be created due to errors."))
    else:
        form = ImageForm()

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
        'max_filesize': MAX_UPLOAD_SIZE,
    })
Пример #15
0
def add(request):
    ImageForm = get_image_form()
    ImageModel = get_image_model()

    if request.POST:
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image)
        if form.is_valid():
            form.save()

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

            messages.success(request,
                             _("Image '{0}' added.").format(image.title))
            return redirect('wagtailimages_index')
        else:
            messages.error(request,
                           _("The image could not be created due to errors."))
    else:
        form = ImageForm()

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
    })
Пример #16
0
def add(request):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    if request.POST:
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image)
        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
            for backend in get_search_backends():
                backend.add(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()

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
    })
Пример #17
0
def chooser(request):
    Image = get_image_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm(user=request.user)
    else:
        uploadform = None

    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)

    if ('q' in request.GET or 'p' in request.GET or 'tag' in request.GET
            or 'collection_id' in request.GET):
        # this request is triggered from search, pagination or 'popular tags';
        # we will just render the results.html fragment
        collection_id = request.GET.get('collection_id')
        if collection_id:
            images = images.filter(collection=collection_id)

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

            images = images.search(q)
            is_searching = True
        else:
            is_searching = False
            q = None

            tag_name = request.GET.get('tag')
            if tag_name:
                images = images.filter(tags__name=tag_name)

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

        return render(
            request, "wagtailimages/chooser/results.html", {
                'images': images,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
    else:
        paginator, images = paginate(request, images, per_page=12)

        context = get_chooser_context(request)
        context.update({
            'images': images,
            'uploadform': uploadform,
        })
        return render_modal_workflow(request,
                                     'wagtailimages/chooser/chooser.html',
                                     'wagtailimages/chooser/chooser.js',
                                     context)
Пример #18
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 image.is_editable_by_user(request.user):
        raise PermissionDenied

    if request.POST:
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image)
        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()
            form.save()

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

            messages.success(request, _("Image '{0}' updated.").format(image.title), buttons=[
                messages.button(reverse('wagtailimages_edit_image', 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)

    # 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

    # Get file size
    try:
        filesize = image.file.size
    except OSError:
        # File doesn't exist
        filesize = None
        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_image', args=(image.id,)), _('Delete'))
        ])

    return render(request, "wagtailimages/images/edit.html", {
        'image': image,
        'form': form,
        'url_generator_enabled': url_generator_enabled,
        'filesize': filesize,
    })
Пример #19
0
def chooser(request):
    Image = get_image_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm()
    else:
        uploadform = None

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

    q = None
    if 'q' in request.GET or 'p' in request.GET or 'tag' in request.GET:
        # this request is triggered from search, pagination or 'popular tags';
        # we will just render the results.html fragment

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

            images = images.search(q)
            is_searching = True
        else:
            is_searching = False

            tag_name = request.GET.get('tag')
            if tag_name:
                images = images.filter(tags__name=tag_name)

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

        return render(
            request, "wagtailimages/chooser/results.html", {
                'images': images,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
    else:
        searchform = SearchForm()

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

    return render_modal_workflow(
        request, 'wagtailimages/chooser/chooser.html',
        'wagtailimages/chooser/chooser.js', {
            'images': images,
            'uploadform': uploadform,
            'searchform': searchform,
            'is_searching': False,
            'query_string': q,
            'will_select_format': request.GET.get('select_format'),
            'popular_tags': Image.popular_tags(),
        })
Пример #20
0
    def test_fields(self):
        form = get_image_form(Image)

        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'tags',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
        ])
Пример #21
0
    def test_focal_point_fields(self):
        form = get_image_form(WagtailImage)

        self.assertIsInstance(form.base_fields['focal_point_x'], forms.IntegerField)
        self.assertIsInstance(form.base_fields['focal_point_y'], forms.IntegerField)
        self.assertIsInstance(form.base_fields['focal_point_width'], forms.IntegerField)
        self.assertIsInstance(form.base_fields['focal_point_height'], forms.IntegerField)

        self.assertIsInstance(form.base_fields['focal_point_x'].widget, forms.HiddenInput)
        self.assertIsInstance(form.base_fields['focal_point_y'].widget, forms.HiddenInput)
        self.assertIsInstance(form.base_fields['focal_point_width'].widget, forms.HiddenInput)
        self.assertIsInstance(form.base_fields['focal_point_height'].widget, forms.HiddenInput)
Пример #22
0
    def test_fields(self):
        form = get_image_form(Image)

        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'tags',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
        ])
Пример #23
0
    def test_focal_point_fields(self):
        form = get_image_form(WagtailImage)

        self.assertIsInstance(form.base_fields['focal_point_x'], forms.IntegerField)
        self.assertIsInstance(form.base_fields['focal_point_y'], forms.IntegerField)
        self.assertIsInstance(form.base_fields['focal_point_width'], forms.IntegerField)
        self.assertIsInstance(form.base_fields['focal_point_height'], forms.IntegerField)

        self.assertIsInstance(form.base_fields['focal_point_x'].widget, forms.HiddenInput)
        self.assertIsInstance(form.base_fields['focal_point_y'].widget, forms.HiddenInput)
        self.assertIsInstance(form.base_fields['focal_point_width'].widget, forms.HiddenInput)
        self.assertIsInstance(form.base_fields['focal_point_height'].widget, forms.HiddenInput)
Пример #24
0
def chooser(request):
    Image = get_image_model()

    if request.user.has_perm('wagtailimages.add_image'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm()
    else:
        uploadform = None

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

    q = None
    if 'q' in request.GET or 'p' in request.GET or 'tag' in request.GET:
        # this request is triggered from search, pagination or 'popular tags';
        # we will just render the results.html fragment

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

            images = images.search(q)
            is_searching = True
        else:
            is_searching = False

            tag_name = request.GET.get('tag')
            if tag_name:
                images = images.filter(tags__name=tag_name)

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

        return render(request, "wagtailimages/chooser/results.html", {
            'images': images,
            'is_searching': is_searching,
            'query_string': q,
            'will_select_format': request.GET.get('select_format')
        })
    else:
        searchform = SearchForm()

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

    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js', {
        'images': images,
        'uploadform': uploadform,
        'searchform': searchform,
        'is_searching': False,
        'query_string': q,
        'will_select_format': request.GET.get('select_format'),
        'popular_tags': Image.popular_tags(),
    })
Пример #25
0
def add(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    if request.method == 'POST':
        if not request.is_ajax():
            return HttpResponseBadRequest("Cannot POST to this view without AJAX")

        if not request.FILES:
            return HttpResponseBadRequest("Must upload a file")

        # Build a form for validation
        form = ImageForm({
            'title': request.FILES['files[]'].name,
        }, {
            'file': request.FILES['files[]'],
        })

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

            # Success! Send back an edit form for this image to the user
            return json_response({
                'success': True,
                'image_id': int(image.id),
                'form': render_to_string('wagtailimages/multiple/edit_form.html', {
                    'image': image,
                    'form': get_image_edit_form(Image)(instance=image, prefix='image-%d' % image.id),
                }, request=request),
            })
        else:
            # Validation error
            return json_response({
                'success': False,

                # https://github.com/django/django/blob/stable/1.6.x/django/forms/util.py#L45
                'error_message': '\n'.join(['\n'.join([force_text(i) for i in v]) for k, v in form.errors.items()]),
            })
    else:
        form = ImageForm()

    return render(request, 'wagtailimages/multiple/add.html', {
        'max_filesize': form.fields['file'].max_upload_size,
        'help_text': form.fields['file'].help_text,
        'allowed_extensions': ALLOWED_EXTENSIONS,
        'error_max_file_size': form.fields['file'].error_messages['file_too_large_unknown_size'],
        'error_accepted_file_types': form.fields['file'].error_messages['invalid_image'],
    })
Пример #26
0
    def test_admin_form_fields_attribute(self):
        form = get_image_form(CustomImage)

        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'tags',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
            'caption',
        ])
Пример #27
0
    def test_admin_form_fields_attribute(self):
        form = get_image_form(CustomImageWithAdminFormFields)

        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'tags',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
            'caption',
        ])
Пример #28
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)
Пример #29
0
def chooser(request):
    Image = get_image_model()

    if request.user.has_perm('wagtailimages.add_image'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm()
    else:
        uploadform = None

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

            images = Image.objects.search(q)
            is_searching = True
        else:
            images = Image.objects.order_by('-created_at')
            is_searching = False

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

        return render(
            request, "wagtailimages/chooser/results.html", {
                'images': images,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
    else:
        searchform = SearchForm()

        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': uploadform,
            'searchform': searchform,
            'is_searching': False,
            'query_string': q,
            'will_select_format': request.GET.get('select_format'),
            'popular_tags': Image.popular_tags(),
        })
Пример #30
0
def get_image_edit_form(ImageModel):
    ImageForm = get_image_form(ImageModel)

    # Make a new form with the file and focal point fields excluded
    class ImageEditForm(ImageForm):
        class Meta(ImageForm.Meta):
            model = ImageModel
            exclude = (
                'file',
                'focal_point_x',
                'focal_point_y',
                'focal_point_width',
                'focal_point_height',
            )

    return ImageEditForm
Пример #31
0
    def test_admin_form_fields_attribute(self):
        form = get_image_form(CustomImageWithAdminFormFields)

        self.assertEqual(
            list(form.base_fields.keys()),
            [
                "title",
                "file",
                "tags",
                "focal_point_x",
                "focal_point_y",
                "focal_point_width",
                "focal_point_height",
                "caption",
            ],
        )
Пример #32
0
def get_image_edit_form(ImageModel):
    ImageForm = get_image_form(ImageModel)

    # Make a new form with the file and focal point fields excluded
    class ImageEditForm(ImageForm):
        class Meta(ImageForm.Meta):
            model = ImageModel
            exclude = (
                'file',
                'focal_point_x',
                'focal_point_y',
                'focal_point_width',
                'focal_point_height',
            )

    return ImageEditForm
Пример #33
0
def poster_image_upload(request, embed_id):
    Image = get_image_model()
    ImageForm = get_image_form()

    searchform = SearchForm()

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

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

            # Reindex the image to make sure all tags are indexed
            for backend in get_search_backends():
                backend.add(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
                embed = Embed.objects.get(id=embed_id)
                embed_image = EmbedVideoPosterImage(embed=embed, image=image)
                embed_image.save()
                image_json = get_image_json(image)
                return render_modal_workflow(
                    request, None, 'wagtailimages/chooser/poster_image_chosen.js',
                    {'image_json': image_json, 'posterimage_id': embed_image.id}
                )
    else:
        form = ImageForm()

    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,
            'max_filesize': MAX_UPLOAD_SIZE,
            'embed_id': embed_id
        }
    )
Пример #34
0
def add(request):
    ImageForm = get_image_form()
    ImageModel = get_image_model()

    if request.POST:
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image)
        if form.is_valid():
            form.save()
            messages.success(request, _("Image '{0}' added.").format(image.title))
            return redirect("wagtailimages_index")
        else:
            messages.error(request, _("The image could not be created due to errors."))
    else:
        form = ImageForm()

    return render(request, "wagtailimages/images/add.html", {"form": form})
Пример #35
0
def chooser_upload(request):
    Image = get_image_model()
    ImageForm = get_image_form()

    searchform = SearchForm()

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

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

            # Reindex the image to make sure all tags are indexed
            for backend in get_search_backends():
                backend.add(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()

    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,
            'max_filesize': MAX_UPLOAD_SIZE
        })
Пример #36
0
    def save_image(self, file_path):
        Image = get_image_model()
        ImageForm = get_image_form(Image)

        if self.is_bmp_format(file_path):
            file_path = self.convert_bmp_image(file_path)

        f=open(file_path, 'r')
        myfile = File(f)


        form = ImageForm({'title': self.title}, {'file': myfile})

        #form.is_valid() == True
        image = form.save(commit=False)
        if self.user is not None:
            image.uploaded_by_user = self.user
        image.save()

        return image
Пример #37
0
def add(request):
    ImageForm = get_image_form()
    ImageModel = get_image_model()

    if request.POST:
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image)
        if form.is_valid():
            form.save()
            messages.success(request, "Image '%s' added." % image.title)
            return redirect('wagtailimages_index')
        else:
            messages.error(request,
                           "The image could not be created due to errors.")
    else:
        form = ImageForm()

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
    })
Пример #38
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
            for backend in get_search_backends():
                backend.add(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},
    )
Пример #39
0
def edit(request, image_id):
    Image = get_image_model()
    ImageForm = get_image_form()

    image = get_object_or_404(Image, id=image_id)

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

    if request.POST:
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image)
        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()
            form.save()
            messages.success(request, _("Image '{0}' updated.").format(image.title))
            return redirect('wagtailimages_index')
        else:
            messages.error(request, _("The image could not be saved due to errors."))
    else:
        form = ImageForm(instance=image)

    # 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

    return render(request, "wagtailimages/images/edit.html", {
        'image': image,
        'form': form,
        'url_generator_enabled': url_generator_enabled,
    })
Пример #40
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}
    )
Пример #41
0
    def test_custom_image_model_without_admin_form_fields_raises_warning(self):
        self.reset_warning_registry()
        with warnings.catch_warnings(record=True) as raw_warnings:
            form = get_image_form(CustomImageWithoutAdminFormFields)

            # Check that a RemovedInWagtail12Warning has been triggered

            # Ignore any ResourceWarnings. TODO: remove this when we've stopped ResourceWarnings from happening...
            try:
                clean_warnings = [
                    w for w in raw_warnings
                    if not issubclass(w.category, ResourceWarning)
                ]
            except NameError:  # ResourceWarning only exists on Python >= 3.2
                clean_warnings = raw_warnings

            self.assertEqual(len(clean_warnings), 1)
            self.assertTrue(
                issubclass(clean_warnings[-1].category,
                           RemovedInWagtail12Warning))
            self.assertTrue(
                "Add admin_form_fields = (tuple of field names) to CustomImageWithoutAdminFormFields"
                in str(clean_warnings[-1].message))

        # All fields, including the not editable one should be on the form
        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
            'caption',
            'not_editable_field',
            'tags',
        ])
Пример #42
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),
        })
Пример #43
0
import os
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.core.exceptions import ObjectDoesNotExist

from wagtail.wagtailimages.models import get_folder_model
from wagtail.wagtailimages.permissions import permission_policy
from wagtail.wagtailimages import get_image_model
from wagtail.wagtailsearch import index as search_index
from wagtail.wagtailimages.utils import get_image_dict
from wagtail.wagtailimages.forms import get_image_form
from wagtail.wagtailimages.fields import ALLOWED_EXTENSIONS

ImageFolder = get_folder_model()
Image = get_image_model()
ImageForm = get_image_form(Image)


@require_POST
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"
Пример #44
0
def chooser(request):
    Image = get_image_model()

    if request.user.has_perm('wagtailimages.add_image'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm()
    else:
        uploadform = None

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

            # page number
            p = request.GET.get("p", 1)

            images = Image.search(q, results_per_page=12, page=p)

            is_searching = True

        else:
            images = Image.objects.order_by('-created_at')
            p = request.GET.get("p", 1)
            paginator = Paginator(images, 12)

            try:
                images = paginator.page(p)
            except PageNotAnInteger:
                images = paginator.page(1)
            except EmptyPage:
                images = paginator.page(paginator.num_pages)

            is_searching = False

        return render(request, "wagtailimages/chooser/results.html", {
            'images': images,
            'is_searching': is_searching,
            'query_string': q,
            'will_select_format': request.GET.get('select_format')
        })
    else:
        searchform = SearchForm()

        images = Image.objects.order_by('-created_at')
        p = request.GET.get("p", 1)
        paginator = Paginator(images, 12)

        try:
            images = paginator.page(p)
        except PageNotAnInteger:
            images = paginator.page(1)
        except EmptyPage:
            images = paginator.page(paginator.num_pages)

    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js', {
        'images': images,
        'uploadform': uploadform,
        'searchform': searchform,
        'is_searching': False,
        'query_string': q,
        'will_select_format': request.GET.get('select_format'),
        'popular_tags': Image.popular_tags(),
    })
Пример #45
0
    def test_file_field(self):
        form = get_image_form(WagtailImage)

        self.assertIsInstance(form.base_fields['file'], WagtailImageField)
        self.assertIsInstance(form.base_fields['file'].widget, forms.FileInput)
Пример #46
0
    def test_tags_field(self):
        form = get_image_form(WagtailImage)

        self.assertIsInstance(form.base_fields['tags'], TagField)
        self.assertIsInstance(form.base_fields['tags'].widget, TagWidget)
Пример #47
0
def add(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    # Filter by folder
    ImageFolder = get_folder_model()
    current_folder = None
    folder_id = request.GET.get('folder')
    if folder_id:
        print("folder id in url")
        try:
            current_folder = ImageFolder.objects.get(id=folder_id)
        except (ValueError, ImageFolder.DoesNotExist):
            pass

    collections = permission_policy.collections_user_has_permission_for(request.user, 'add')
    if len(collections) > 1:
        collections_to_choose = collections
    else:
        # no need to show a collections chooser
        collections_to_choose = None

    if request.method == 'POST':
        if not request.is_ajax():
            return HttpResponseBadRequest("Cannot POST to this view without AJAX")

        if not request.FILES:
            return HttpResponseBadRequest("Must upload a file")

        # Build a form for validation
        form = ImageForm({
            'title': request.FILES['files[]'].name,
            'collection': request.POST.get('collection'),
        }, {
            'file': request.FILES['files[]'],
        }, 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
            if current_folder:
                # If we have a current folder - add image to it
                image.folder = current_folder
            image.save()

            # Success! Send back an edit form for this image to the user
            return JsonResponse({
                'success': True,
                'image_id': int(image.id),
                'form': render_to_string('wagtailimages/multiple/edit_form.html', {
                    'image': image,
                    'form': get_image_edit_form(Image)(
                        instance=image, prefix='image-%d' % image.id, user=request.user
                    ),
                }, request=request),
            })
        else:
            # Validation error
            return JsonResponse({
                'success': False,

                # https://github.com/django/django/blob/stable/1.6.x/django/forms/util.py#L45
                'error_message': '\n'.join(['\n'.join([force_text(i) for i in v]) for k, v in form.errors.items()]),
            })
    else:
        form = ImageForm(user=request.user)

    return render(request, 'wagtailimages/multiple/add.html', {
        'current_folder' : current_folder,
        'max_filesize': form.fields['file'].max_upload_size,
        'help_text': form.fields['file'].help_text,
        'allowed_extensions': ALLOWED_EXTENSIONS,
        'error_max_file_size': form.fields['file'].error_messages['file_too_large_unknown_size'],
        'error_accepted_file_types': form.fields['file'].error_messages['invalid_image'],
        'collections': collections_to_choose,
    })
Пример #48
0
def chooser(request):
    Image = get_image_model()

    if request.user.has_perm("wagtailimages.add_image"):
        ImageForm = get_image_form()
        uploadform = ImageForm()
    else:
        uploadform = None

    q = None
    if "q" in request.GET or "p" in request.GET:
        searchform = SearchForm(request.GET)
        if searchform.is_valid():
            q = searchform.cleaned_data["q"]

            # page number
            p = request.GET.get("p", 1)

            images = Image.search(q, results_per_page=10, page=p)

            is_searching = True

        else:
            images = Image.objects.order_by("-created_at")
            p = request.GET.get("p", 1)
            paginator = Paginator(images, 10)

            try:
                images = paginator.page(p)
            except PageNotAnInteger:
                images = paginator.page(1)
            except EmptyPage:
                images = paginator.page(paginator.num_pages)

            is_searching = False

        return render(
            request,
            "wagtailimages/chooser/results.html",
            {
                "images": images,
                "is_searching": is_searching,
                "query_string": q,
                "will_select_format": request.GET.get("select_format"),
            },
        )
    else:
        searchform = SearchForm()

        images = Image.objects.order_by("-created_at")
        p = request.GET.get("p", 1)
        paginator = Paginator(images, 10)

        try:
            images = paginator.page(p)
        except PageNotAnInteger:
            images = paginator.page(1)
        except EmptyPage:
            images = paginator.page(paginator.num_pages)

    return render_modal_workflow(
        request,
        "wagtailimages/chooser/chooser.html",
        "wagtailimages/chooser/chooser.js",
        {
            "images": images,
            "uploadform": uploadform,
            "searchform": searchform,
            "is_searching": False,
            "query_string": q,
            "will_select_format": request.GET.get("select_format"),
            "popular_tags": Image.popular_tags(),
        },
    )
Пример #49
0
def multichooser(request):
    collection_id = request.GET.get('collection_id', None)
    if not collection_id:
        album_title = request.GET.get('album_title')
        page_id = request.GET.get('page_id', None)
        parent_page_id = request.GET.get('parent_page_id', None)
        collection = get_or_create_collection(album_title, page_id,
                                              parent_page_id)
    else:
        collection = Collection.objects.get(id=collection_id)

    Image = get_image_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm(user=request.user)
    else:
        uploadform = None

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

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

    q = None
    if ('q' in request.GET or 'p' in request.GET or 'tag' in request.GET):
        # this request is triggered from search, pagination or 'popular tags';
        # we will just render the results.html fragment

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

            images = images.search(q)
            is_searching = True
        else:
            is_searching = False

            tag_name = request.GET.get('tag')
            if tag_name:
                images = images.filter(tags__name=tag_name)

        # Pagination
        paginator, images = paginate(request, images, per_page=20)

        return render(
            request, "fotoalben/multichooser/results.html", {
                'images': images,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
    else:
        searchform = SearchForm()
        #        this_site = Site.find_for_request( request )
        #        collections = Collection.objects.all()
        #        if len(collections) < 2:
        #            collections = None

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

        return render_modal_workflow(
            request, 'fotoalben/multichooser/multichooser.html',
            'fotoalben/multichooser/multichooser.js', {
                'images': images,
                'uploadform': uploadform,
                'searchform': searchform,
                'is_searching': False,
                'query_string': q,
                'will_select_format': request.GET.get('select_format'),
                'popular_tags': popular_tags_for_model(Image),
                'collections': [collection],
                'collection': collection,
                'page_id': page_id,
                'album_title': album_title,
                'parent_page_id': parent_page_id
            })
Пример #50
0
    def test_tags_field(self):
        form = get_image_form(WagtailImage)

        self.assertIsInstance(form.base_fields['tags'], TagField)
        self.assertIsInstance(form.base_fields['tags'].widget, TagWidget)
Пример #51
0
    def test_file_field(self):
        form = get_image_form(WagtailImage)

        self.assertIsInstance(form.base_fields['file'], WagtailImageField)
        self.assertIsInstance(form.base_fields['file'].widget, forms.FileInput)
Пример #52
0
def chooser(request):
    Image = get_image_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm(user=request.user)
    else:
        uploadform = None

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

    q = None
    if (
        'q' in request.GET or 'p' in request.GET or 'tag' in request.GET or
        'collection_id' in request.GET
    ):
        # this request is triggered from search, pagination or 'popular tags';
        # we will just render the results.html fragment
        collection_id = request.GET.get('collection_id')
        if collection_id:
            images = images.filter(collection=collection_id)

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

            images = images.search(q)
            is_searching = True
        else:
            is_searching = False

            tag_name = request.GET.get('tag')
            if tag_name:
                images = images.filter(tags__name=tag_name)

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

        return render(request, "wagtailimages/chooser/results.html", {
            'images': images,
            'is_searching': is_searching,
            'query_string': q,
            'will_select_format': request.GET.get('select_format')
        })
    else:
        searchform = SearchForm()

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

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

    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js', {
        'images': images,
        'uploadform': uploadform,
        'searchform': searchform,
        'is_searching': False,
        'query_string': q,
        'will_select_format': request.GET.get('select_format'),
        'popular_tags': popular_tags_for_model(Image),
        'collections': collections,
    })
Пример #53
0
def chooser(request):
    Image = get_image_model()
    ImageFolder = get_folder_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        ImageForm = get_image_form(Image)
        uploadform = ImageForm(user=request.user)
        ImageFolderForm = get_folder_form(ImageFolder)
    else:
        uploadform = None

    # Get images (filtered by user permission)
    images = permission_policy.instances_user_has_any_permission_for(
        request.user, ['change', 'delete']
    ).order_by('-created_at')

    # Check if folders_only
    folders_only = request.GET.get('folders_only')
    if folders_only:
        folders_only = True
    else:
        folders_only = False

    # Filter by folder
    folders = ImageFolder.objects.filter(folder__isnull = True)
    current_folder = None
    folder_id = request.GET.get('folder')
    if folder_id:
        try:
            current_folder = ImageFolder.objects.get(id=folder_id)
            images = Image.objects.filter(folder=current_folder)
        except (ValueError, ImageFolder.DoesNotExist):
            pass

    q = None
    if (
        'q' in request.GET or 'p' in request.GET or 'tag' in request.GET or
        'collection_id' in request.GET or
        'folder' in request.GET
    ):
        # this request is triggered from search, pagination or 'popular tags';
        # we will just render the results.html fragment
        collection_id = request.GET.get('collection_id')
        if collection_id:
            images = images.filter(collection=collection_id)

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

            images = images.search(q)
            is_searching = True
        else:
            is_searching = False

            tag_name = request.GET.get('tag')
            if tag_name:
                images = images.filter(tags__name=tag_name)

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

        if not folders_only:
            return render(request, "wagtailimages/chooser/results.html", {
                'images': images,
                'folders' : folders,
                'current_folder' : current_folder,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
        else:
            return render(request, "wagtailimages/chooser/folders.html", {
                'images': images,
                'folders': folders,
                'current_folder': current_folder,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
    else:
        searchform = SearchForm()

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

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

    return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js', {
        'images': images,
        'folders' : folders,
        'current_folder' : current_folder,
        'uploadform': uploadform,
        'searchform': searchform,
        'is_searching': False,
        'query_string': q,
        'will_select_format': request.GET.get('select_format'),
        'popular_tags': popular_tags_for_model(Image),
        'collections': collections,
    })
def add(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    # Filter by folder
    ImageFolder = get_folder_model()
    current_folder = None
    folder_id = request.GET.get('folder')
    if folder_id:
        try:
            current_folder = ImageFolder.objects.get(id=folder_id)
        except (ValueError, ImageFolder.DoesNotExist):
            pass

    collections = permission_policy.collections_user_has_permission_for(
        request.user, 'add')
    if len(collections) > 1:
        collections_to_choose = collections
    else:
        # no need to show a collections chooser
        collections_to_choose = None

    if request.method == 'POST':
        if not request.is_ajax():
            return HttpResponseBadRequest(
                "Cannot POST to this view without AJAX")

        if not request.FILES:
            return HttpResponseBadRequest("Must upload a file")

        # Build a form for validation
        form = ImageForm(
            {
                'title': request.FILES['files[]'].name,
                'collection': request.POST.get('collection'),
            }, {
                'file': request.FILES['files[]'],
            },
            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
            if current_folder:
                # If we have a current folder - add image to it
                image.folder = current_folder
            image.save()

            # Success! Send back an edit form for this image to the user
            return JsonResponse({
                'success':
                True,
                'image_id':
                int(image.id),
                'form':
                render_to_string('wagtailimages/multiple/edit_form.html', {
                    'image':
                    image,
                    'form':
                    get_image_edit_form(Image)(instance=image,
                                               prefix='image-%d' % image.id,
                                               user=request.user),
                },
                                 request=request),
            })
        else:
            # Validation error
            return JsonResponse({
                'success':
                False,

                # https://github.com/django/django/blob/stable/1.6.x/django/forms/util.py#L45
                'error_message':
                '\n'.join([
                    '\n'.join([force_text(i) for i in v])
                    for k, v in form.errors.items()
                ]),
            })
    else:
        form = ImageForm(user=request.user)

    return render(
        request, 'wagtailimages/multiple/add.html', {
            'current_folder':
            current_folder,
            'max_filesize':
            form.fields['file'].max_upload_size,
            'help_text':
            form.fields['file'].help_text,
            'allowed_extensions':
            ALLOWED_EXTENSIONS,
            'error_max_file_size':
            form.fields['file'].error_messages['file_too_large_unknown_size'],
            'error_accepted_file_types':
            form.fields['file'].error_messages['invalid_image'],
            'collections':
            collections_to_choose,
        })
Пример #55
0
def chooser(request):
    Image = get_image_model()

    if request.user.has_perm('wagtailimages.add_image'):
        ImageForm = get_image_form()
        uploadform = ImageForm()
    else:
        uploadform = None

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

            # page number
            p = request.GET.get("p", 1)

            images = Image.search(q, results_per_page=10, page=p)

            is_searching = True

        else:
            images = Image.objects.order_by('-created_at')
            p = request.GET.get("p", 1)
            paginator = Paginator(images, 10)

            try:
                images = paginator.page(p)
            except PageNotAnInteger:
                images = paginator.page(1)
            except EmptyPage:
                images = paginator.page(paginator.num_pages)

            is_searching = False

        return render(
            request, "wagtailimages/chooser/results.html", {
                'images': images,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
    else:
        searchform = SearchForm()

        images = Image.objects.order_by('-created_at')
        p = request.GET.get("p", 1)
        paginator = Paginator(images, 10)

        try:
            images = paginator.page(p)
        except PageNotAnInteger:
            images = paginator.page(1)
        except EmptyPage:
            images = paginator.page(paginator.num_pages)

    return render_modal_workflow(
        request, 'wagtailimages/chooser/chooser.html',
        'wagtailimages/chooser/chooser.js', {
            'images': images,
            'uploadform': uploadform,
            'searchform': searchform,
            'is_searching': False,
            'query_string': q,
            'will_select_format': request.GET.get('select_format'),
            'popular_tags': Image.popular_tags(),
        })