Esempio n. 1
0
def add(request, media_type):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    if request.POST:
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(request.POST,
                         request.FILES,
                         instance=media,
                         user=request.user)
        if form.is_valid():
            try:
                messages.info(
                    request,
                    _(f"'{media.title.capitalize()}' is being processed"))
                chunk_upload_path = upload_path(media.title)
                messages.info(request,
                              _(f"chunk_upload_path = '{chunk_upload_path}'"))
                uploaded_file = chunk_uploaded_file(request.FILES['file'],
                                                    media.filename,
                                                    chunk_upload_path)
                print(
                    f'after uploaded file. uploaded_file Var is {uploaded_file}'
                )
                # May need to make the chunk uploaded file method save into an intermediary model for this to work
                form.instance.file = File(uploaded_file,
                                          os.path.basename(uploaded_file.path))
                print(
                    'after form.instance.file. Above form.save. About to form.save()'
                )
                form.save()
                print('form saved!')
                # Ensure the uploaded_file is closed because calling save() will open the file and read its content.
                uploaded_file.close()
                uploaded_file.delete()

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

                messages.success(
                    request,
                    _(f"'{media.title.capitalize()}' successfully uploaded!."),
                    buttons=[
                        messages.button(reverse('chunked_media:index'),
                                        _('Index'))
                    ])
                return redirect('chunked_media:index')
            except Exception as e:
                messages.error(
                    request,
                    _(f"{media.title} could not be saved due to: {e}."))
        else:
            messages.error(
                request, _("The media file could not be saved due to errors."))
    else:
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(user=request.user, instance=media)

    return render(request, "chunked_media/media/add.html", {
        'form': form,
        'media_type': media_type,
    })
Esempio n. 2
0
def edit(request, media_id):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    media = get_object_or_404(Media, id=media_id)

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

    if request.POST:
        original_file = media.file
        form = MediaForm(request.POST,
                         request.FILES,
                         instance=media,
                         user=request.user)
        if form.is_valid():
            if 'file' in form.changed_data:
                # if providing a new media file, delete the old one.
                # NB Doing this via original_file.delete() clears the file field,
                # which definitely isn't what we want...
                original_file.storage.delete(original_file.name)
            messages.info(
                request, _(f"'{media.title.capitalize()}' is being processed"))
            chunk_upload_path = upload_path(media.title)
            uploaded_file = chunk_uploaded_file(request.FILES['file'],
                                                media.filename,
                                                chunk_upload_path)
            # May need to make the chunk uploaded file method save into an intermediary model for this to work
            form.instance.file = File(uploaded_file,
                                      os.path.basename(uploaded_file.path))
            form.save()
            # Ensure the uploaded_file is closed because calling save() will open the file and read its content.
            uploaded_file.close()
            uploaded_file.delete()

            # media = save_final_media_to_model(chunk_uploaded_file(request.FILES['file'],
            #                                                       media.filename,
            #                                                       chunk_upload_path))

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

            messages.success(request,
                             _(f"{media.title.capitalize()} updated"),
                             buttons=[
                                 messages.button(
                                     reverse('chunked_media:edit',
                                             args=(media.id, )), _('Edit'))
                             ])
            return redirect('chunked_media:index')
        else:
            messages.error(request,
                           _("The media could not be saved due to errors."))
    else:
        form = MediaForm(instance=media, user=request.user)

    filesize = None

    # Get file size when there is a file associated with the Media object
    if media.file:
        try:
            filesize = media.file.size
        except OSError:
            # File doesn't exist
            pass

    if not filesize:
        messages.error(
            request,
            _("The file could not be found. Please change the source or delete the media file"
              ),
            buttons=[
                messages.button(
                    reverse('chunked_media:delete', args=(media.id, )),
                    _('Delete'))
            ])

    return render(
        request, "chunked_media/media/edit.html", {
            'media':
            media,
            'filesize':
            filesize,
            'form':
            form,
            'user_can_delete':
            permission_policy.user_has_permission_for_instance(
                request.user, 'delete', media),
        })
Esempio n. 3
0
def custom_admin_round_copy_view(request, page):
    # Custom view to handle copied Round pages.
    # https://github.com/wagtail/wagtail/blob/124827911463f0cb959edbb9d8d5685578540bd3/wagtail/admin/views/pages.py#L824

    # Parent page defaults to parent of source page
    parent_page = page.get_parent()

    # Check if the user has permission to publish subpages on the parent
    can_publish = parent_page.permissions_for_user(request.user).can_publish_subpage()

    form = CopyForm(request.POST or None, user=request.user, page=page, can_publish=can_publish)

    next_url = get_valid_next_url_from_request(request)

    # Prefill parent_page in case the form is invalid (as prepopulated value for the form field,
    # because ModelChoiceField seems to not fall back to the user given value)
    parent_page = Page.objects.get(id=request.POST['new_parent_page'])

    if form.is_valid():
        # Receive the parent page (this should never be empty)
        if form.cleaned_data['new_parent_page']:
            parent_page = form.cleaned_data['new_parent_page']

        if not page.permissions_for_user(request.user).can_copy_to(parent_page,
                                                                   form.cleaned_data.get('copy_subpages')):
            raise PermissionDenied

        # Re-check if the user has permission to publish subpages on the new parent
        can_publish = parent_page.permissions_for_user(request.user).can_publish_subpage()

        # Copy the page
        new_page = page.copy(
            recursive=form.cleaned_data.get('copy_subpages'),
            to=parent_page,
            update_attrs={
                'title': form.cleaned_data['new_title'],
                'slug': form.cleaned_data['new_slug'],
                'start_date': None,
                'end_date': None,
            },
            keep_live=(can_publish and form.cleaned_data.get('publish_copies')),
            user=request.user,
        )

        messages.info(request, _((
            "Please select the date in the copied page. "
            "Newly copied pages have NONE value for the start and end date"
        )))

        # Give a success message back to the user
        if form.cleaned_data.get('copy_subpages'):
            messages.success(
                request, _("Page '{0}' and {1} subpages copied.").format(
                    page.get_admin_display_title(), new_page.get_descendants().count()
                )
            )
        else:
            messages.success(request, _("Page '{0}' copied.").format(page.get_admin_display_title()))

        for fn in hooks.get_hooks('after_copy_page'):
            result = fn(request, page, new_page)
            if hasattr(result, 'status_code'):
                return result

        # Redirect to explore of parent page
        if next_url:
            return redirect(next_url)
        return redirect('wagtailadmin_explore', parent_page.id)