Beispiel #1
0
    def test_filtering_tags(self):
        get_image_model().objects.get(id=6).tags.add('test')

        response = self.get_response(tags='test')
        content = json.loads(response.content.decode('UTF-8'))

        image_id_list = self.get_image_id_list(content)
        self.assertEqual(image_id_list, [6])
Beispiel #2
0
    def test_filtering_tags(self):
        get_image_model().objects.get(id=6).tags.add('test')

        response = self.get_response(tags='test')
        content = json.loads(response.content.decode('UTF-8'))

        image_id_list = self.get_image_id_list(content)
        self.assertEqual(image_id_list, [6])
Beispiel #3
0
def chooser_select_format(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    if request.POST:
        form = ImageInsertionForm(request.POST, initial={'alt_text': image.default_alt_text})
        if form.is_valid():

            format = get_image_format(form.cleaned_data['format'])
            preview_image = image.get_rendition(format.filter_spec)

            image_json = json.dumps({
                'id': image.id,
                'title': image.title,
                'format': format.name,
                'alt': form.cleaned_data['alt_text'],
                'class': format.classnames,
                'preview': {
                    'url': preview_image.url,
                    'width': preview_image.width,
                    'height': preview_image.height,
                },
                'html': format.image_to_editor_html(image, form.cleaned_data['alt_text']),
            })

            return render_modal_workflow(
                request, None, 'wagtailimages/chooser/image_chosen.js',
                {'image_json': image_json}
            )
    else:
        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}
    )
Beispiel #4
0
    def get_dict_for_field(self, field_name):
        try:
            field = self.model._meta.get_field(field_name)
            label = getattr(field, 'verbose_name', None)
            value = getattr(self.instance, field_name, None)
            if label is None:
                label = field.name
            try:
                fieldtype = field.get_internal_type()
                if fieldtype == 'ForeignKey':
                    if field.related_model == get_image_model():
                        fieldtype = 'image'
                        value = self.get_value_for_image_field(field_name)
                    if field.related_model == Document:
                        fieldtype = 'document'
                        value = self.get_value_for_document_field(field_name)
            except AttributeError:
                fieldtype = 'related'
                value = self.get_value_for_relationship_field(field_name)
        except FieldDoesNotExist:
            label = field_name
            fieldtype = ''

        return {
            'label': label.capitalize(),
            'type': fieldtype,
            'value': value
        }
Beispiel #5
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(),
    })
Beispiel #6
0
def generate_url(request, image_id, filter_spec):
    # Get the image
    Image = get_image_model()
    try:
        image = Image.objects.get(id=image_id)
    except Image.DoesNotExist:
        return json_response({
            'error': "Cannot find image."
        }, status=404)

    # Check if this user has edit permission on this image
    if not image.is_editable_by_user(request.user):
        return json_response({
            'error': "You do not have permission to generate a URL for this image."
        }, status=403)

    # Parse the filter spec to make sure its valid
    if not Filter(spec=filter_spec).is_valid():
        return json_response({
            'error': "Invalid filter spec."
        }, status=400)

    # Generate url
    signature = generate_signature(image_id, filter_spec)
    url = reverse('wagtailimages_serve', args=(signature, image_id, filter_spec))

    # Get site root url
    try:
        site_root_url = Site.objects.get(is_default_site=True).root_url
    except Site.DoesNotExist:
        site_root_url = Site.objects.first().root_url

    return json_response({'url': site_root_url + url, 'local_url': url}, status=200)
Beispiel #7
0
def generate_url(request, image_id, filter_spec):
    # Get the image
    Image = get_image_model()
    try:
        image = Image.objects.get(id=image_id)
    except Image.DoesNotExist:
        return JsonResponse({"error": "Cannot find image."}, status=404)

    # Check if this user has edit permission on this image
    if not permission_policy.user_has_permission_for_instance(request.user, "change", image):
        return JsonResponse({"error": "You do not have permission to generate a URL for this image."}, status=403)

    # Parse the filter spec to make sure its valid
    try:
        Filter(spec=filter_spec).operations
    except InvalidFilterSpecError:
        return JsonResponse({"error": "Invalid filter spec."}, status=400)

    # Generate url
    signature = generate_signature(image_id, filter_spec)
    url = reverse("wagtailimages_serve", args=(signature, image_id, filter_spec))

    # Get site root url
    try:
        site_root_url = Site.objects.get(is_default_site=True).root_url
    except Site.DoesNotExist:
        site_root_url = Site.objects.first().root_url

    # Generate preview url
    preview_url = reverse("wagtailimages:preview", args=(image_id, filter_spec))

    return JsonResponse({"url": site_root_url + url, "preview_url": preview_url}, status=200)
Beispiel #8
0
def search(request):
    Image = get_image_model()
    images = []
    q = None
    is_searching = False

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

            # page number
            p = request.GET.get("p", 1)
            is_searching = True
            images = Image.search(q, results_per_page=20, page=p)
    else:
        form = SearchForm()

    if request.is_ajax():
        return render(request, "wagtailimages/images/results.html", {
            'images': images,
            'is_searching': is_searching,
            'search_query': q,
        })
    else:
        return render(request, "wagtailimages/images/index.html", {
            'form': form,
            'images': images,
            'is_searching': is_searching,
            'popular_tags': Image.popular_tags(),
            'search_query': q,
        })
Beispiel #9
0
def get_image_form():
    return modelform_factory(
        get_image_model(),
        # set the 'file' widget to a FileInput rather than the default ClearableFileInput
        # so that when editing, we don't get the 'currently: ...' banner which is
        # a bit pointless here
        widgets={'file': forms.FileInput()})
Beispiel #10
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,
    })
Beispiel #11
0
def edit(request, image_id, callback=None):
    Image = get_image_model()
    ImageForm = get_image_edit_form()

    image = get_object_or_404(Image, id=image_id)

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

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

    form = ImageForm(request.POST, request.FILES, instance=image, prefix='image-'+image_id)

    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)

        return json_response({
            'success': True,
            'image_id': int(image_id),
        })
    else:
        return json_response({
            'success': False,
            'image_id': int(image_id),
            'form': render_to_string('wagtailimages/multiple/edit_form.html', {
                'image': image,
                'form': form,
            }, context_instance=RequestContext(request)),
        })
Beispiel #12
0
    def get_field_display_value(self, field_name, field=None):
        """ Return a display value for a field """
        """
        Firstly, check for a 'get_fieldname_display' property/method on
        the model, and return the value of that, if present.
        """
        val_funct = getattr(self.instance, 'get_%s_display' % field_name, None)
        if val_funct is not None:
            if callable(val_funct):
                return val_funct()
            return val_funct
        """
        Secondly, if we have a real field, we can try to display something
        more useful for it.
        """
        if field is not None:
            try:
                field_type = field.get_internal_type()
                if (field_type == 'ForeignKey'
                        and field.related_model == get_image_model()):
                    # The field is an image
                    return self.get_image_field_display(field_name, field)

                if (field_type == 'ForeignKey'
                        and field.related_model == Document):
                    # The field is a document
                    return self.get_document_field_display(field_name, field)

            except AttributeError:
                pass
        """
        Resort to getting the value of 'field_name' from the instance.
        """
        return getattr(self.instance, field_name,
                       self.model_admin.get_empty_value_display())
Beispiel #13
0
def generate_url(request, image_id, filter_spec):
    # Get the image
    Image = get_image_model()
    try:
        image = Image.objects.get(id=image_id)
    except Image.DoesNotExist:
        return json_response({
            'error': "Cannot find image."
        }, status=404)

    # Check if this user has edit permission on this image
    if not image.is_editable_by_user(request.user):
        return json_response({
            'error': "You do not have permission to generate a URL for this image."
        }, status=403)

    # Parse the filter spec to make sure its valid
    if not Filter(spec=filter_spec).is_valid():
        return json_response({
            'error': "Invalid filter spec."
        }, status=400)

    # Generate url
    signature = generate_signature(image_id, filter_spec)
    url = reverse('wagtailimages_serve', args=(signature, image_id, filter_spec))

    # Get site root url
    try:
        site_root_url = Site.objects.get(is_default_site=True).root_url
    except Site.DoesNotExist:
        site_root_url = Site.objects.first().root_url

    return json_response({'url': site_root_url + url, 'local_url': url}, status=200)
Beispiel #14
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}
    )
Beispiel #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,
        'max_filesize': MAX_UPLOAD_SIZE,
    })
Beispiel #16
0
    def test_offset_total_count(self):
        response = self.get_response(offset=10)
        content = json.loads(response.content.decode('UTF-8'))

        # The total count must not be affected by "offset"
        self.assertEqual(content['meta']['total_count'],
                         get_image_model().objects.count())
Beispiel #17
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
                                 })
Beispiel #18
0
def preview(request, image_id, filter_spec):
    image = get_object_or_404(get_image_model(), id=image_id)

    try:
        return Filter(spec=filter_spec).process_image(image.file.file, HttpResponse(content_type='image/jpeg'), focal_point=image.get_focal_point())
    except Filter.InvalidFilterSpecError:
        return HttpResponse("Invalid filter spec: " + filter_spec, content_type='text/plain', status=400)
Beispiel #19
0
def preview(request, image_id, filter_spec):
    image = get_object_or_404(get_image_model(), id=image_id)

    try:
        return Filter(spec=filter_spec).run(image, HttpResponse(content_type='image/jpeg'))
    except InvalidFilterSpecError:
        return HttpResponse("Invalid filter spec: " + filter_spec, content_type='text/plain', status=400)
def create_thumbnail(model_instance):
    # http://stackoverflow.com/a/25648427/1179222
    from wagtail.wagtailimages.models import get_image_model
    WagtailImage = get_image_model()

    # CREATING IMAGE FROM THUMBNAIL
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()
    if backend.__class__.__name__ == 'YoutubeBackend':
        if thumbnail_url.endswith('hqdefault.jpg'):
            for resolution in YOUTUBE_RESOLUTIONS:
                temp_thumbnail_url = thumbnail_url.replace(
                    'hqdefault.jpg', resolution)
                if checkUrl(temp_thumbnail_url):
                    thumbnail_url = temp_thumbnail_url
                    break

    img_temp = NamedTemporaryFile(delete=True)
    try:
        img_temp.write(urllib2.urlopen(thumbnail_url).read())
    except:
        http = urllib3.PoolManager()
        img_temp.write(http.request('GET', thumbnail_url).data)
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Beispiel #21
0
def chooser_select_format(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    if request.POST:
        form = ImageInsertionForm(request.POST, initial={"alt_text": image.default_alt_text})
        if form.is_valid():

            format = get_image_format(form.cleaned_data["format"])
            preview_image = image.get_rendition(format.filter_spec)

            image_json = json.dumps(
                {
                    "id": image.id,
                    "title": image.title,
                    "format": format.name,
                    "alt": form.cleaned_data["alt_text"],
                    "class": format.classnames,
                    "preview": {"url": preview_image.url, "width": preview_image.width, "height": preview_image.height},
                    "html": format.image_to_editor_html(image, form.cleaned_data["alt_text"]),
                }
            )

            return render_modal_workflow(
                request, None, "wagtailimages/chooser/image_chosen.js", {"image_json": image_json}
            )
    else:
        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},
    )
Beispiel #22
0
def chooser_select_format(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    if request.POST:
        form = ImageInsertionForm(request.POST, initial={'alt_text': image.default_alt_text})
        if form.is_valid():

            format = get_image_format(form.cleaned_data['format'])
            preview_image = image.get_rendition(format.filter_spec)

            image_json = json.dumps({
                'id': image.id,
                'title': image.title,
                'format': format.name,
                'alt': form.cleaned_data['alt_text'],
                'class': format.classnames,
                'preview': {
                    'url': preview_image.url,
                    'width': preview_image.width,
                    'height': preview_image.height,
                },
                'html': format.image_to_editor_html(image, form.cleaned_data['alt_text']),
            })

            return render_modal_workflow(
                request, None, 'wagtailimages/chooser/image_chosen.js',
                {'image_json': image_json}
            )
    else:
        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}
    )
Beispiel #23
0
def image_chosen(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    return render_modal_workflow(
        request, None, 'wagtailimages/chooser/image_chosen.js',
        {'image_json': get_image_json(image)}
    )
Beispiel #24
0
    def test_basic(self):
        response = self.get_response()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-type'], 'application/json')

        # Will crash if the JSON is invalid
        content = json.loads(response.content.decode('UTF-8'))

        # Check that the meta section is there
        self.assertIn('meta', content)
        self.assertIsInstance(content['meta'], dict)

        # Check that the total count is there and correct
        self.assertIn('total_count', content['meta'])
        self.assertIsInstance(content['meta']['total_count'], int)
        self.assertEqual(content['meta']['total_count'], get_image_model().objects.count())

        # Check that the images section is there
        self.assertIn('images', content)
        self.assertIsInstance(content['images'], list)

        # Check that each image has a meta section with type and detail_url attributes
        for image in content['images']:
            self.assertIn('meta', image)
            self.assertIsInstance(image['meta'], dict)
            self.assertEqual(set(image['meta'].keys()), {'type', 'detail_url'})

            # Type should always be wagtailimages.Image
            self.assertEqual(image['meta']['type'], 'wagtailimages.Image')

            # Check detail url
            self.assertEqual(image['meta']['detail_url'], 'http://localhost/api/v1/images/%d/' % image['id'])
Beispiel #25
0
 def render(self):
     return render_to_string('wagtailadmin/home/site_summary.html', {
         'total_pages': Page.objects.count() - 1,  # subtract 1 because the root node is not a real page
         'total_images': get_image_model().objects.count(),
         'total_docs': Document.objects.count(),
         'search_form': SearchForm(),
     }, RequestContext(self.request))
Beispiel #26
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,
    })
Beispiel #27
0
def search(request):
    Image = get_image_model()
    images = []
    q = None
    is_searching = False

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

            # page number
            p = request.GET.get("p", 1)
            is_searching = True
            images = Image.search(q, results_per_page=20, page=p)
    else:
        form = SearchForm()

    if request.is_ajax():
        return render(request, "wagtailimages/images/results.html", {
            'images': images,
            'is_searching': is_searching,
            'search_query': q,
        })
    else:
        return render(
            request, "wagtailimages/images/index.html", {
                'form': form,
                'images': images,
                'is_searching': is_searching,
                'popular_tags': Image.popular_tags(),
                'search_query': q,
            })
Beispiel #28
0
def image_chosen(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    return render_modal_workflow(
        request, None, 'wagtailimages/chooser/image_chosen.js',
        {'image_json': get_image_json(image)}
    )
def create_thumbnail(model_instance):
    # http://stackoverflow.com/a/25648427/1179222
    from wagtail.wagtailimages.models import get_image_model
    WagtailImage = get_image_model()

    # CREATING IMAGE FROM THUMBNAIL
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()
    if backend.__class__.__name__ == 'YoutubeBackend':
        if thumbnail_url.endswith('hqdefault.jpg'):
            for resolution in YOUTUBE_RESOLUTIONS:
                temp_thumbnail_url = thumbnail_url.replace(
                    'hqdefault.jpg', resolution)
                if checkUrl(temp_thumbnail_url):
                    thumbnail_url = temp_thumbnail_url
                    break

    img_temp = NamedTemporaryFile(delete=True)
    try:
        img_temp.write(urllib2.urlopen(thumbnail_url).read())
    except:
        http = urllib3.PoolManager()
        img_temp.write(http.request('GET', thumbnail_url).data)
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Beispiel #30
0
def preview(request, image_id, filter_spec):
    image = get_object_or_404(get_image_model(), id=image_id)

    try:
        return Filter(spec=filter_spec).run(image, HttpResponse(content_type='image/jpeg'))
    except InvalidFilterSpecError:
        return HttpResponse("Invalid filter spec: " + filter_spec, content_type='text/plain', status=400)
Beispiel #31
0
    def test_basic(self):
        response = self.get_response()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-type'], 'application/json')

        # Will crash if the JSON is invalid
        content = json.loads(response.content.decode('UTF-8'))

        # Check that the meta section is there
        self.assertIn('meta', content)
        self.assertIsInstance(content['meta'], dict)

        # Check that the total count is there and correct
        self.assertIn('total_count', content['meta'])
        self.assertIsInstance(content['meta']['total_count'], int)
        self.assertEqual(content['meta']['total_count'], get_image_model().objects.count())

        # Check that the items section is there
        self.assertIn('items', content)
        self.assertIsInstance(content['items'], list)

        # Check that each image has a meta section with type and detail_url attributes
        for image in content['items']:
            self.assertIn('meta', image)
            self.assertIsInstance(image['meta'], dict)
            self.assertEqual(set(image['meta'].keys()), {'type', 'detail_url', 'tags'})

            # Type should always be wagtailimages.Image
            self.assertEqual(image['meta']['type'], 'wagtailimages.Image')

            # Check detail url
            self.assertEqual(image['meta']['detail_url'], 'http://localhost/api/v2beta/images/%d/' % image['id'])
Beispiel #32
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,
    })
Beispiel #33
0
    def __init__(self, image_url, scrape_dir='scrape_images', user=None, title=None, tags=[]):

        self.tags = tags
        self.title = title
        self.user = user
        self.scrape_dir = scrape_dir
        self.image_url = self.to_unicode_or_bust(image_url)
        self.decoded_url = self.decode_url()
        self.filename = self.get_filename_from_url()

        if self.title is  None:
            self.title = self.filename


        Image = get_image_model()

        try:
            self.image = Image.objects.get(title=self.title)
        except Image.DoesNotExist:
            print u"Getting image"
            tmp_image = self.get_image()
            self.image = self.save_image(tmp_image)
        except Image.MultipleObjectsReturned:
            print u"Found multiple images, using first"
            self.image = Image.objects.filter(title=self.title).first()
        else:
            print u"Found image in database"

        self.add_tags()
Beispiel #34
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},
    )
Beispiel #35
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,
    })
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,
    })
Beispiel #37
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})
Beispiel #38
0
def index(request):
    Image = get_image_model()

    q = None
    p = request.GET.get("p", 1)
    is_searching = False

    if 'q' in request.GET:
        form = SearchForm(request.GET, placeholder_suffix="images")
        if form.is_valid():
            q = form.cleaned_data['q']

            is_searching = True
            if not request.user.has_perm('wagtailimages.change_image'):
                # restrict to the user's own images
                images = Image.search(
                    q,
                    results_per_page=20,
                    page=p,
                    filters={'uploaded_by_user_id': request.user.id})
            else:
                images = Image.search(q, results_per_page=20, page=p)
        else:
            images = Image.objects.order_by('-created_at')
            if not request.user.has_perm('wagtailimages.change_image'):
                # restrict to the user's own images
                images = images.filter(uploaded_by_user=request.user)
    else:
        images = Image.objects.order_by('-created_at')
        if not request.user.has_perm('wagtailimages.change_image'):
            # restrict to the user's own images
            images = images.filter(uploaded_by_user=request.user)
        form = SearchForm(placeholder_suffix="images")

    if not is_searching:
        paginator = Paginator(images, 20)

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

    if request.is_ajax():
        return render(request, "wagtailimages/images/results.html", {
            'images': images,
            'is_searching': is_searching,
            'search_query': q,
        })
    else:
        return render(
            request, "wagtailimages/images/index.html", {
                'search_form': form,
                'images': images,
                'is_searching': is_searching,
                'popular_tags': Image.popular_tags(),
                'search_query': q,
            })
Beispiel #39
0
def get_image_form_for_multi():
    # exclude the file widget
    return modelform_factory(get_image_model(), exclude=('file',), widgets={
        'focal_point_x': forms.HiddenInput(attrs={'class': 'focal_point_x'}),
        'focal_point_y': forms.HiddenInput(attrs={'class': 'focal_point_y'}),
        'focal_point_width': forms.HiddenInput(attrs={'class': 'focal_point_width'}),
        'focal_point_height': forms.HiddenInput(attrs={'class': 'focal_point_height'}),
    })
Beispiel #40
0
class ImagesAPIEndpoint(BaseAPIEndpoint):
    base_serializer_class = ImageSerializer
    filter_backends = [FieldsFilter, OrderingFilter, SearchFilter]
    extra_body_fields = ['title', 'width', 'height']
    extra_meta_fields = ['tags']
    default_fields = ['title', 'tags']
    name = 'images'
    model = get_image_model()
Beispiel #41
0
def preview(request, image_id, filter_spec):
    image = get_object_or_404(get_image_model(), id=image_id)

    try:
        response, image_format = Filter(spec=filter_spec).run(image, HttpResponse())
        response['Content-Type'] = 'image/' + image_format
        return response
    except InvalidFilterSpecError:
        return HttpResponse("Invalid filter spec: " + filter_spec, content_type='text/plain', status=400)
def usage(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    paginator, used_by = paginate(request, image.get_usage())

    return render(request, "wagtailimages/images/usage.html", {
        'image': image,
        'used_by': used_by
    })
Beispiel #43
0
def index(request):
    Image = get_image_model()

    # Get images
    images = Image.objects.order_by("-created_at")

    # Permissions
    if not request.user.has_perm("wagtailimages.change_image"):
        # restrict to the user's own images
        images = images.filter(uploaded_by_user=request.user)

    # Search
    query_string = None
    if "q" in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search images"))
        if form.is_valid():
            query_string = form.cleaned_data["q"]

            is_searching = True
            if not request.user.has_perm("wagtailimages.change_image"):
                # restrict to the user's own images
                images = Image.search(query_string, filters={"uploaded_by_user_id": request.user.id})
            else:
                images = Image.search(query_string)
    else:
        form = SearchForm(placeholder=_("Search images"))

    # Pagination
    p = request.GET.get("p", 1)
    paginator = Paginator(images, 20)

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

    # Create response
    if request.is_ajax():
        return render(
            request,
            "wagtailimages/images/results.html",
            {"images": images, "query_string": query_string, "is_searching": bool(query_string)},
        )
    else:
        return render(
            request,
            "wagtailimages/images/index.html",
            {
                "images": images,
                "query_string": query_string,
                "is_searching": bool(query_string),
                "search_form": form,
                "popular_tags": Image.popular_tags(),
            },
        )
Beispiel #44
0
def preview(request, image_id, filter_spec):
    image = get_object_or_404(get_image_model(), id=image_id)

    try:
        response, image_format = Filter(spec=filter_spec).run(image, HttpResponse())
        response['Content-Type'] = 'image/' + image_format
        return response
    except InvalidFilterSpecError:
        return HttpResponse("Invalid filter spec: " + filter_spec, content_type='text/plain', status=400)
Beispiel #45
0
def index(request):
    Image = get_image_model()

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

    # Permissions
    if not request.user.has_perm('wagtailimages.change_image'):
        # restrict to the user's own images
        images = images.filter(uploaded_by_user=request.user)

    # Search
    query_string = None
    if 'q' in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search images"))
        if form.is_valid():
            query_string = form.cleaned_data['q']

            is_searching = True
            if not request.user.has_perm('wagtailimages.change_image'):
                # restrict to the user's own images
                images = Image.search(
                    query_string,
                    filters={'uploaded_by_user_id': request.user.id})
            else:
                images = Image.search(query_string)
    else:
        form = SearchForm(placeholder=_("Search images"))

    # Pagination
    p = request.GET.get('p', 1)
    paginator = Paginator(images, 20)

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

    # Create response
    if request.is_ajax():
        return render(
            request, 'wagtailimages/images/results.html', {
                'images': images,
                'query_string': query_string,
                'is_searching': bool(query_string),
            })
    else:
        return render(
            request, 'wagtailimages/images/index.html', {
                'images': images,
                'query_string': query_string,
                'is_searching': bool(query_string),
                'search_form': form,
                'popular_tags': Image.popular_tags(),
            })
Beispiel #46
0
def usage(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    paginator, used_by = paginate(request, image.get_usage())

    return render(request, "wagtailimages/images/usage.html", {
        'image': image,
        'used_by': used_by
    })
Beispiel #47
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,
    })
Beispiel #48
0
def url_generator(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

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

    form = URLGeneratorForm(initial={"filter_method": "original", "width": image.width, "height": image.height})

    return render(request, "wagtailimages/images/url_generator.html", {"image": image, "form": form})
Beispiel #49
0
def url_generator(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

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

    form = URLGeneratorForm(initial={"filter_method": "original", "width": image.width, "height": image.height})

    return render(request, "wagtailimages/images/url_generator.html", {"image": image, "form": form})
Beispiel #50
0
def describe_collection_docs(collection):
    images_count = get_image_model().objects.filter(collection=collection).count()
    if images_count:
        url = urlresolvers.reverse("wagtailimages:index") + ("?collection_id=%d" % collection.id)
        return {
            "count": images_count,
            "count_text": ungettext("%(count)s image", "%(count)s images", images_count) % {"count": images_count},
            "url": url,
        }
Beispiel #51
0
def index(request):
    Image = get_image_model()

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

    # Search
    query_string = None
    if "q" in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search images"))
        if form.is_valid():
            query_string = form.cleaned_data["q"]

            images = images.search(query_string)
    else:
        form = SearchForm(placeholder=_("Search images"))

    # Filter by collection
    current_collection = None
    collection_id = request.GET.get("collection_id")
    if collection_id:
        try:
            current_collection = Collection.objects.get(id=collection_id)
            images = images.filter(collection=current_collection)
        except (ValueError, Collection.DoesNotExist):
            pass

    paginator, images = paginate(request, images)

    collections = permission_policy.collections_user_has_any_permission_for(request.user, ["add", "change"])
    if len(collections) < 2:
        collections = None

    # Create response
    if request.is_ajax():
        return render(
            request,
            "wagtailimages/images/results.html",
            {"images": images, "query_string": query_string, "is_searching": bool(query_string)},
        )
    else:
        return render(
            request,
            "wagtailimages/images/index.html",
            {
                "images": images,
                "query_string": query_string,
                "is_searching": bool(query_string),
                "search_form": form,
                "popular_tags": Image.popular_tags(),
                "collections": collections,
                "current_collection": current_collection,
                "user_can_add": permission_policy.user_has_permission(request.user, "add"),
            },
        )
Beispiel #52
0
class ImagesAPIEndpoint(BaseAPIEndpoint):
    model = get_image_model()

    def get_queryset(self, request):
        return self.model.objects.all()

    def get_api_fields(self, model):
        api_fields = ['title', 'width', 'height']
        api_fields.extend(super(ImagesAPIEndpoint, self).get_api_fields(model))
        return api_fields

    def listing_view(self, request):
        queryset = self.get_queryset(request)

        # Check query paramters
        self.check_query_paramters(request, queryset)

        # Filtering
        queryset = self.do_field_filtering(request, queryset)

        # Ordering
        queryset = self.do_ordering(request, queryset)

        # Search
        queryset = self.do_search(request, queryset)

        # Pagination
        total_count = queryset.count()
        queryset = self.do_pagination(request, queryset)

        # Get list of fields to show in results
        if 'fields' in request.GET:
            fields = request.GET['fields'].split(',')
        else:
            fields = ('title', )

        return self.json_response(
            OrderedDict([
                ('meta', OrderedDict([
                    ('total_count', total_count),
                ])),
                ('images', [
                    self.serialize_object(image,
                                          fields=fields,
                                          base_url=get_base_url(request))
                    for image in queryset
                ]),
            ]))

    def detail_view(self, request, pk):
        image = get_object_or_404(self.get_queryset(request), pk=pk)
        data = self.serialize_object(image,
                                     all_fields=True,
                                     base_url=get_base_url(request))

        return self.json_response(data)
Beispiel #53
0
    def test_tags(self):
        image = get_image_model().objects.get(id=5)
        image.tags.add('hello')
        image.tags.add('world')

        response = self.get_response(5)
        content = json.loads(response.content.decode('UTF-8'))

        self.assertIn('tags', content)
        self.assertEqual(content['tags'], ['hello', 'world'])
Beispiel #54
0
 def render(self):
     return render_to_string(
         'wagtailadmin/home/site_summary.html',
         {
             'total_pages': Page.objects.count() -
             1,  # subtract 1 because the root node is not a real page
             'total_images': get_image_model().objects.count(),
             'total_docs': Document.objects.count(),
         },
         RequestContext(self.request))
Beispiel #55
0
class ImagesAPIEndpoint(BaseAPIEndpoint):
    queryset = get_image_model().objects.all().order_by('id')
    base_serializer_class = ImageSerializer
    filter_backends = [FieldsFilter, OrderingFilter, SearchFilter]
    extra_api_fields = ['title', 'tags', 'width', 'height']
    name = 'images'

    @classmethod
    def has_model(cls, model):
        return model == get_image_model()
Beispiel #56
0
    def test_s3_files_use_secure_urls(self):
        image_file = get_test_image_file(filename='test.png')

        Image = get_image_model()
        image = Image(file=image_file)

        self.assertEqual(
            image.file.url,
            'https://s3.amazonaws.com/test_s3_bucket/root/test.png'
        )