Esempio n. 1
0
def delete(request, folder_id):
    ImageFolder = get_folder_model()
    folder = get_object_or_404(ImageFolder, id=folder_id)

    if request.method == 'POST':
        # POST if confirmation of delete

        # try find a parent folder
        parent_folder = folder.get_parent()

        # Delete folder
        folder.delete()

        # Success! Send back to index or image specific folder
        response = redirect('wagtailimages:index')
        if parent_folder:
            response['Location'] += '?folder={0}'.format(parent_folder.id)
        return response

    return render(
        request,
        'wagtailimages/folder/confirm_delete.html',
        {
            'folder': folder,
            # 'form': form,
        })
def add(request, add_to_folder=False):
    ImageFolder = get_folder_model()
    ImageFolderForm = get_folder_form(ImageFolder)

    parent_folder = False
    if add_to_folder:
        parent_folder = get_object_or_404(ImageFolder, id=add_to_folder)

    if request.method == 'POST':
        # Build a form for validation
        form = ImageFolderForm(request.POST)
        error = True

        if form.is_valid():
            error = False

            folder = ImageFolder(
                title=form.cleaned_data['title'].strip()
            )
            if parent_folder:
                folder.folder = parent_folder

            try:
                # Check if the folder is present in the DB or physically present in the OS
                folder.validate_folder()
            except ValidationError as e:
                error = True
                form._errors['title'] = e.message

        if not error:
            # Save folder
            folder.save()

            # Success! Send back to index or image specific folder
            response = redirect('wagtailimages:index')
            response['Location'] += '?folder={0}'.format(folder.id)
            return response
        else:
            # Validation error
            return render(request, 'wagtailimages/folder/add.html', {
                'error_message': 'Error adding folder',
                'help_text': '',
                'parent_folder': parent_folder,
                'form': form,
            })
    else:
        form = ImageFolderForm()

        return render(request, 'wagtailimages/folder/add.html', {
            'help_text': '',
            'parent_folder': parent_folder,
            'form': form,
        })
Esempio n. 3
0
def add(request, add_to_folder=False):
    ImageFolder = get_folder_model()
    ImageFolderForm = get_folder_form(ImageFolder)

    parent_folder = False
    if add_to_folder:
        parent_folder = get_object_or_404(ImageFolder, id=add_to_folder)

    if request.method == 'POST':
        # Build a form for validation
        form = ImageFolderForm(request.POST)
        error = True

        if form.is_valid():
            error = False

            folder = ImageFolder(title=form.cleaned_data['title'].strip())
            if parent_folder:
                folder.folder = parent_folder

            try:
                # Check if the folder is present in the DB or physically present in the OS
                folder.validate_folder()
            except ValidationError as e:
                error = True
                form._errors['title'] = e.message

        if not error:
            # Save folder
            folder.save()

            # Success! Send back to index or image specific folder
            response = redirect('wagtailimages:index')
            response['Location'] += '?folder={0}'.format(folder.id)
            return response
        else:
            # Validation error
            return render(
                request, 'wagtailimages/folder/add.html', {
                    'error_message': 'Error adding folder',
                    'help_text': '',
                    'parent_folder': parent_folder,
                    'form': form,
                })
    else:
        form = ImageFolderForm()

        return render(request, 'wagtailimages/folder/add.html', {
            'help_text': '',
            'parent_folder': parent_folder,
            'form': form,
        })
Esempio n. 4
0
def edit(request, folder_id):
    ImageFolder = get_folder_model()
    ImageFolderForm = get_folder_form(ImageFolder)
    folder = get_object_or_404(ImageFolder, id=folder_id)

    if request.method == 'POST':
        # Build a form for validation
        form = ImageFolderForm(request.POST)

        if form.is_valid():

            folder.title = form.cleaned_data['title']

            try:
                # Check if the folder is present in the DB or physically present in the OS
                folder.validate_folder()
            except ValidationError as e:
                form._errors['title'] = e.message
                # Validation error
                return render(
                    request, 'wagtailimages/folder/edit.html', {
                        'error_message': 'Error adding folder',
                        'help_text': '',
                        'form': form,
                    })

            folder.save()

            # Success! Send back to index or image specific folder
            response = redirect('wagtailimages:index')
            response['Location'] += '?folder={0}'.format(folder.id)
            return response
        else:
            # Validation error
            return render(
                request, 'wagtailimages/folder/edit.html', {
                    'error_message': 'Error adding folder',
                    'help_text': '',
                    'form': form,
                })
    else:
        form = ImageFolderForm(instance=folder)

    return render(request, 'wagtailimages/folder/edit.html', {
        'help_text': '',
        'folder': folder,
        'form': form,
    })
def edit(request, folder_id):
    ImageFolder = get_folder_model()
    ImageFolderForm = get_folder_form(ImageFolder)
    folder = get_object_or_404(ImageFolder, id=folder_id)

    if request.method == 'POST':
        # Build a form for validation
        form = ImageFolderForm(request.POST)

        if form.is_valid():

            folder.title = form.cleaned_data['title']

            try:
                # Check if the folder is present in the DB or physically present in the OS
                folder.validate_folder()
            except ValidationError as e:
                form._errors['title'] = e.message
                # Validation error
                return render(request, 'wagtailimages/folder/edit.html', {
                    'error_message': 'Error adding folder',
                    'help_text': '',
                    'form': form,
                })

            folder.save()

            # Success! Send back to index or image specific folder
            response = redirect('wagtailimages:index')
            response['Location'] += '?folder={0}'.format(folder.id)
            return response
        else:
            # Validation error
            return render(request, 'wagtailimages/folder/edit.html', {
                'error_message': 'Error adding folder',
                'help_text': '',
                'form': form,
            })
    else:
        form = ImageFolderForm(instance=folder)

    return render(request, 'wagtailimages/folder/edit.html', {
        'help_text': '',
        'folder': folder,
        'form': form,
    })
Esempio n. 6
0
def delete(request, folder_id):
    Image = get_image_model()
    ImageFolder = get_folder_model()
    folder = get_object_or_404(ImageFolder, id=folder_id)

    # Make Sure folder contains no images
    images = Image.objects.filter(folder=folder)

    if images.count() > 0:
        error = True
        error_text = "Cannot delete folder containing images"
    else:
        error = False
        error_text = ""

    # Make sure folder contains no sub folders
    if not error and ImageFolder.objects.filter(folder=folder).count() > 0:
        error = True
        error_text = "Cannot delete folder containing subfolders"

    if not error and request.method == 'POST':
        # POST if confirmation of delete

        # try find a parent folder
        parent_folder = folder.get_parent()

        # Delete folder
        folder.delete()

        # Success! Send back to index or image specific folder
        response = redirect('wagtailimages:index')
        if parent_folder:
            response['Location'] += '?folder={0}'.format(parent_folder.id)
        return response

    return render(
        request,
        'wagtailimages/folder/confirm_delete.html',
        {
            'error': error,
            'error_text': error_text,
            'folder': folder,
            #'form': form,
        })
Esempio n. 7
0
def custom_index(request):

    root_folder = dict()
    root_folder['id'] = '-1'
    root_folder['title'] = 'root'

    # Get all folders under root
    ImageFolder = get_folder_model()
    folders = ImageFolder.objects.filter(folder__isnull=True)
    folders_list = get_folders_list(folders)
    root_folder['sub_folders'] = folders_list

    # Get all images under root
    Image = get_image_model()
    images = Image.objects.filter(folder__isnull=True)
    root_folder['images'] = list()
    for image in images:
        root_folder['images'].append(get_image_dict(image))

    return render(request, 'wagtailimages/images/custom_index.html', {
        'folders': [root_folder],
    })
def delete(request, folder_id):
    ImageFolder = get_folder_model()
    folder = get_object_or_404(ImageFolder, id=folder_id)

    if request.method == 'POST':
        # POST if confirmation of delete

        # try find a parent folder
        parent_folder = folder.get_parent()

        # Delete folder
        folder.delete()

        # Success! Send back to index or image specific folder
        response = redirect('wagtailimages:index')
        if parent_folder:
            response['Location'] += '?folder={0}'.format(parent_folder.id)
        return response

    return render(request, 'wagtailimages/folder/confirm_delete.html', {
        'folder': folder,
        # 'form': form,
    })
Esempio n. 9
0
def edit(request, folder_id):
    ImageFolder = get_folder_model()
    ImageFolderForm = get_folder_form(ImageFolder)

    folder = get_object_or_404(ImageFolder, id=folder_id)

    if request.method == 'POST':
        # Build a form for validation
        form = ImageFolderForm(request.POST)

        if form.is_valid():
            #TODO - Check for clashing filenames
            # Save folder
            folder.title = form.cleaned_data['title']
            folder.save()

            # Success! Send back to index or image specific folder
            response = redirect('wagtailimages:index')
            response['Location'] += '?folder={0}'.format(folder.id)
            return response
        else:
            # Validation error
            return render(
                request, 'wagtailimages/folder/edit.html', {
                    'error_message': 'Error adding folder',
                    'help_text': '',
                    'form': form,
                })
    else:
        form = ImageFolderForm(instance=folder)

    return render(request, 'wagtailimages/folder/edit.html', {
        'help_text': '',
        'folder': folder,
        'form': form,
    })
Esempio n. 10
0
def add(request, add_to_folder=False):
    ImageFolder = get_folder_model()
    ImageFolderForm = get_folder_form(ImageFolder)

    parent_folder = False
    if add_to_folder:
        parent_folder = get_object_or_404(ImageFolder, id=add_to_folder)

    if request.method == 'POST':
        # Build a form for validation
        form = ImageFolderForm(request.POST)

        if form.is_valid():
            #TODO - Check for clashing filenames
            error = False

            if parent_folder:
                if ImageFolder.objects.filter(
                        folder=parent_folder,
                        title=form.cleaned_data['title'].strip()).count() > 0:
                    error = True
                    form._errors['title'] = "Folder already exists"
            else:
                if ImageFolder.objects.filter(
                        folder__isnull=True,
                        title=form.cleaned_data['title'].strip()).count() > 0:
                    error = True
                    form._errors['title'] = "Folder already exists"

            if not error:
                # Save folder
                folder = ImageFolder(title=form.cleaned_data['title'].strip())
                if parent_folder:
                    folder.folder = parent_folder
                folder.save()

                # Success! Send back to index or image specific folder
                response = redirect('wagtailimages:index')
                response['Location'] += '?folder={0}'.format(folder.id)
                return response
            else:
                return render(
                    request, 'wagtailimages/folder/add.html', {
                        'error_message': 'Error adding folder',
                        'help_text': '',
                        'parent_folder': parent_folder,
                        'form': form,
                    })
        else:
            # Validation error
            return render(
                request, 'wagtailimages/folder/add.html', {
                    'error_message': 'Error adding folder',
                    'help_text': '',
                    'parent_folder': parent_folder,
                    'form': form,
                })
    else:
        form = ImageFolderForm()

    return render(request, 'wagtailimages/folder/add.html', {
        'help_text': '',
        'parent_folder': parent_folder,
        'form': form,
    })
def index(request):

    # Folders
    ImageFolder = get_folder_model()
    folders = ImageFolder.objects.filter(folder__isnull = True)

    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

    # Filter by folder
    current_folder = None
    folder_id = request.GET.get('folder')
    if folder_id:
        try:
            current_folder = ImageFolder.objects.get(id=folder_id)
            images = images.filter(folder=current_folder)
        except (ValueError, ImageFolder.DoesNotExist):
            print "error getting folder"
            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,
            'folders': folders,
            'current_folder' : current_folder,
            'query_string': query_string,
            'is_searching': bool(query_string),
        })
    else:
        return render(request, 'wagtailimages/images/index.html', {
            'images': images,
            'folders': folders,
            'current_folder' : current_folder,
            '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'),
        })
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,
        })
Esempio n. 13
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"
Esempio n. 14
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,
    })
Esempio n. 15
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,
    })
Esempio n. 16
0
def index(request):

    # Folders
    ImageFolder = get_folder_model()
    folders = ImageFolder.objects.filter(folder__isnull = True)

    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

    # Filter by folder
    current_folder = None
    folder_id = request.GET.get('folder')
    if folder_id:
        try:
            current_folder = ImageFolder.objects.get(id=folder_id)
            images = images.filter(folder=current_folder)
        except (ValueError, ImageFolder.DoesNotExist):
            print("error getting folder")
            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,
            'folders': folders,
            'current_folder': current_folder,
            'query_string': query_string,
            'is_searching': bool(query_string),
        })
    else:
        return render(request, 'wagtailimages/images/index.html', {
            'images': images,
            'folders': folders,
            'current_folder': current_folder,
            'query_string': query_string,
            'is_searching': bool(query_string),

            'search_form': form,
            'popular_tags': popular_tags_for_model(Image),
            'collections': collections,
            'current_collection': current_collection,
            'user_can_add': permission_policy.user_has_permission(request.user, 'add'),
        })