Exemple #1
0
    def test_fields(self):
        form = get_image_form(Image)

        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'collection',
            'tags',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
        ])
Exemple #2
0
    def test_admin_form_fields_attribute(self):
        form = get_image_form(CustomImage)

        self.assertEqual(list(form.base_fields.keys()), [
            'title',
            'file',
            'collection',
            'tags',
            'focal_point_x',
            'focal_point_y',
            'focal_point_width',
            'focal_point_height',
            'caption',
        ])
Exemple #3
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
Exemple #4
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, 'tuiuiuimages/chooser/select_format.html',
                    'tuiuiuimages/chooser/select_format.js', {
                        'image': image,
                        'form': form
                    })
            else:
                # not specifying a format; return the image details now
                return render_modal_workflow(
                    request, None, 'tuiuiuimages/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, 'tuiuiuimages/chooser/chooser.html',
                                 'tuiuiuimages/chooser/chooser.js', {
                                     'images': images,
                                     'uploadform': form,
                                     'searchform': searchform
                                 })
Exemple #5
0
    def test_focal_point_fields(self):
        form = get_image_form(TuiuiuImage)

        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)
Exemple #6
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('tuiuiuimages:edit',
                                             args=(image.id, )), _('Edit'))
                             ])
            return redirect('tuiuiuimages:index')
        else:
            messages.error(request,
                           _("The image could not be created due to errors."))
    else:
        form = ImageForm(user=request.user)

    return render(request, "tuiuiuimages/images/add.html", {
        'form': form,
    })
Exemple #7
0
    def test_tags_field(self):
        form = get_image_form(TuiuiuImage)

        self.assertIsInstance(form.base_fields['tags'], TagField)
        self.assertIsInstance(form.base_fields['tags'].widget, TagWidget)
Exemple #8
0
    def test_file_field(self):
        form = get_image_form(TuiuiuImage)

        self.assertIsInstance(form.base_fields['file'], TuiuiuImageField)
        self.assertIsInstance(form.base_fields['file'].widget, forms.FileInput)
Exemple #9
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)

    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, "tuiuiuimages/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, 'tuiuiuimages/chooser/chooser.html',
            'tuiuiuimages/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,
            })
Exemple #10
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('tuiuiuimages:edit',
                                             args=(image.id, )),
                                     _('Edit again'))
                             ])
            return redirect('tuiuiuimages: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
    # :) foo
    try:
        reverse('tuiuiuimages_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('tuiuiuimages:delete', args=(image.id, )),
                        _('Delete'))
                ])

    return render(
        request, "tuiuiuimages/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),
        })
Exemple #11
0
def add(request):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    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
            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('tuiuiuimages/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, 'tuiuiuimages/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'],
        'collections': collections_to_choose,
    })