示例#1
0
def add(request, media_type):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    if request.method == '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():
            form.save()

            # Reindex the media entry to make sure all tags are indexed
            search_index.insert_or_update_object(media)
            messages.success(request,
                             _("Media file '{0}' added.").format(media.title),
                             buttons=[
                                 messages.button(
                                     reverse('wagtailmedia:edit',
                                             args=(media.id, )), _('Edit'))
                             ])
            return redirect('wagtailmedia:index')
        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, "wagtailmedia/media/add.html", {
        'form': form,
        'media_type': media_type,
    })
示例#2
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():
            form.save()

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

            messages.success(request, _("Media file '{0}' added.").format(media.title), buttons=[
                messages.button(reverse('wagtailmedia:edit', args=(media.id,)), _('Edit'))
            ])
            return redirect('wagtailmedia:index')
        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, "wagtailmedia/media/add.html", {
        'form': form,
        'media_type': media_type,
    })
示例#3
0
 def test_get_media_form_widgets(self):
     Form = get_media_form(models.Media)
     form = Form()
     self.assertIsInstance(form.fields['tags'].widget,
                           widgets.AdminTagWidget)
     self.assertIsInstance(form.fields['file'].widget, forms.FileInput)
     self.assertIsInstance(form.fields['thumbnail'].widget,
                           forms.ClearableFileInput)
示例#4
0
 def _test_form_init_with_non_editable_field(self, media_type, field_name):
     MediaForm = get_media_form(models.Media)
     models.Media._meta.get_field(field_name).editable = False
     media = models.Media.objects.create(title="Test media file", type=media_type, duration=100)
     try:
         MediaForm(media)
     finally:
         models.Media._meta.get_field(field_name).editable = True
示例#5
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)
            media = form.save()

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

            messages.success(request, _("Media file '{0}' updated").format(media.title), buttons=[
                messages.button(reverse('wagtailmedia:edit', args=(media.id,)), _('Edit'))
            ])
            return redirect('wagtailmedia: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('wagtailmedia:delete', args=(media.id,)), _('Delete'))]
        )

    return render(request, "wagtailmedia/media/edit.html", {
        'media': media,
        'filesize': filesize,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', media
        ),
    })
示例#6
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)
            media = form.save()

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

            messages.success(request, _("Media file '{0}' updated").format(media.title), buttons=[
                messages.button(reverse('wagtailmedia:edit', args=(media.id,)), _('Edit'))
            ])
            return redirect('wagtailmedia: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('wagtailmedia:delete', args=(media.id,)), _('Delete'))]
        )

    return render(request, "wagtailmedia/media/edit.html", {
        'media': media,
        'filesize': filesize,
        'form': form,
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', media
        ),
    })
示例#7
0
def chooser_upload(request, media_type):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    if request.method == 'POST':
        media = Media(uploaded_by_user=request.user, type=media_type)
        form = MediaForm(request.POST,
                         request.FILES,
                         instance=media,
                         user=request.user,
                         prefix='media-chooser-upload')
        if form.is_valid():
            form.save()

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

            return render_modal_workflow(request,
                                         None,
                                         None,
                                         None,
                                         json_data={
                                             'step': 'media_chosen',
                                             'result': get_media_json(media)
                                         })

    media_files = permission_policy.instances_user_has_any_permission_for(
        request.user, ['change', 'delete'])

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

    searchform = SearchForm()

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

    media_files = media_files.order_by('-created_at')
    paginator, media_files = paginate(request, media_files, per_page=10)

    context = {
        'media_files': media_files,
        'searchform': searchform,
        'collections': collections,
        'uploadform': form,
        'is_searching': False,
        'pagination_template': pagination_template,
        'media_type': media_type,
    }
    return render_modal_workflow(request,
                                 'wagtailmedia/chooser/chooser.html',
                                 None,
                                 context,
                                 json_data={'step': 'chooser'})
示例#8
0
def chooser(request):
    Media = get_media_model()

    if permission_policy.user_has_permission(request.user, 'add'):
        MediaForm = get_media_form(Media)
        uploadform = MediaForm(user=request.user)
    else:
        uploadform = None

    media_files = Media.objects.order_by('-created_at')

    #May not be necessary.
    for hook in hooks.get_hooks('construct_media_chooser_queryset'):
        media_files = hook(media_files, request)

    if ('q' in request.GET or 'p' in request.GET
            or 'collection_id' in request.GET):
        media_files = Media.objects.order_by('-created_at')

        collection_id = request.GET.get('collection_id')
        if collection_id:
            media_files = media_files.filter(collection=collection_id)

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

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

        # Pagination
        paginator, media_files = paginate(request, media_files, per_page=10)

        return render(
            request, "wagtailmedia/chooser/results.html", {
                'media_files': media_files,
                'query_string': q,
                'is_searching': is_searching,
            })
    else:
        paginator, media_files = paginate(request, media_files, per_page=10)
        context = get_chooser_context(request)

        context.update({
            'media_files': media_files,
            'uploadform': uploadform,
        })

        return render_modal_workflow(request,
                                     'wagtailmedia/chooser/chooser.html',
                                     None,
                                     context,
                                     json_data=get_chooser_js_data())
示例#9
0
 def _test_form_init_with_non_editable_field(self, media_type, field_name):
     MediaForm = get_media_form(Media)
     Media._meta.get_field(field_name).editable = False
     media = Media.objects.create(title="Test media file",
                                  type=media_type,
                                  duration=100)
     try:
         MediaForm(media)
     finally:
         Media._meta.get_field(field_name).editable = True
示例#10
0
def download_video(apps, schema_editor):
    model_classes = [IndustryPageArticleSummary, LandingPageArticleSummary]
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    for model_class in model_classes:
        for model in model_class.objects.all():
            if not hasattr(model, 'video'):
                continue
            video = (
                YouTube(model.video).streams
                .filter(subtype='mp4', progressive=True)
                .order_by('resolution')
                .desc()
                .first()
            )
            thumbnail_url = video.player_config_args['thumbnail_url']
            media = Media(uploaded_by_user=None, type='video')
            video_buffer = video.stream_to_buffer()
            video_buffer.seek(0)
            form = MediaForm(
                {
                    'duration': video.player_config_args['length_seconds'],
                    'title': video.player_config_args['title'],
                    'tags': video.player_config_args['keywords'],
                },
                {
                    'file': SimpleUploadedFile(
                        name=video.player_config_args['title'],
                        content=video_buffer.read(),
                        content_type='video/mp4',
                    ),
                    'thumbnail': SimpleUploadedFile(
                        name=video.player_config_args['title'] +  ' thumbnail',
                        content=requests.get(thumbnail_url).content,
                    )
                },
                instance=media,
                user=None
            )
            assert form.is_valid(), form.errors
            form.save()
            for backend in get_search_backends():
                backend.add(media)

            model.video_media = media
            model.save()
示例#11
0
def chooser_upload(request):
    Media = get_media_model()
    MediaForm = get_media_form(Media)

    if request.method == 'POST':
        media = Media(uploaded_by_user=request.user)
        form = MediaForm(request.POST,
                         request.FILES,
                         instance=media,
                         user=request.user)

        if form.is_valid():
            form.save()
            # Reindex the media to make sure all tags are indexed
            search_index.insert_or_update_object(media)

            return render_modal_workflow(request,
                                         None,
                                         None,
                                         None,
                                         json_data={
                                             'step': 'media_chosen',
                                             'result':
                                             get_media_result_data(media)
                                         })
    else:
        form = MediaForm(user=request.user)

    media_files = Media.objects.order_by('-created_at')

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

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

    context = get_chooser_context(request)
    context.update({
        'media_files': media_files,
        'uploadform': form,
    })
    return render_modal_workflow(request,
                                 'wagtailmedia/chooser/chooser.html',
                                 None,
                                 context,
                                 json_data=get_chooser_js_data())
示例#12
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():
            form.save()

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

            messages.success(
                request,
                _("Media file '{0}' added.").format(media.title),
                buttons=[
                    messages.button(
                        reverse("wagtailmedia:edit", args=(media.id, )),
                        _("Edit"))
                ],
            )
            return redirect("wagtailmedia:index")
        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,
        "wagtailmedia/media/add.html",
        {
            "form": form,
            "media_type": media_type,
        },
    )
示例#13
0
 def test_audio_form_presents_thumbnail(self):
     MediaForm = get_media_form(models.Media)
     media = models.Media.objects.create(title="Test media file", type='audio', duration=100)
     self.assertIn('thumbnail', MediaForm(instance=media).fields.keys())
示例#14
0
def chooser(request):
    media_files = permission_policy.instances_user_has_any_permission_for(
        request.user, ['change', 'delete'])

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

    if permission_policy.user_has_permission(request.user, 'add'):
        Media = get_media_model()
        MediaForm = get_media_form(Media)
        uploadform = MediaForm(user=request.user,
                               prefix='media-chooser-upload')
    else:
        uploadform = None

    q = None
    is_searching = False
    if 'q' in request.GET or 'p' in request.GET or 'collection_id' in request.GET:
        collection_id = request.GET.get('collection_id')
        if collection_id:
            media_files = media_files.filter(collection=collection_id)

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

            media_files = media_files.search(q)
            is_searching = True
        else:
            media_files = media_files.order_by('-created_at')
            is_searching = False

        # Pagination
        paginator, media_files = paginate(request, media_files, per_page=10)

        return render(
            request, "wagtailmedia/chooser/results.html", {
                'media_files': media_files,
                'query_string': q,
                'is_searching': is_searching,
                'pagination_template': pagination_template,
            })
    else:
        searchform = SearchForm()

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

        media_files = media_files.order_by('-created_at')
        paginator, media_files = paginate(request, media_files, per_page=10)

    return render_modal_workflow(
        request,
        'wagtailmedia/chooser/chooser.html',
        None, {
            'media_files': media_files,
            'searchform': searchform,
            'collections': collections,
            'uploadform': uploadform,
            'is_searching': False,
            'pagination_template': pagination_template,
        },
        json_data={
            'step': 'chooser',
            'error_label': "Server Error",
            'error_message':
            "Report this error to your webmaster with the following information:",
            'tag_autocomplete_url': reverse('wagtailadmin_tag_autocomplete'),
        })
示例#15
0
def chooser_upload(request, media_type):
    upload_forms = {}

    if (permission_policy.user_has_permission(request.user, "add")
            and request.method == "POST"):
        Media = get_media_model()
        MediaForm = get_media_form(Media)

        media = Media(uploaded_by_user=request.user, type=media_type)
        uploading_form = MediaForm(
            request.POST,
            request.FILES,
            instance=media,
            user=request.user,
            prefix="media-chooser-upload",
        )
        if uploading_form.is_valid():
            uploading_form.save()

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

            return render_modal_workflow(
                request,
                None,
                None,
                None,
                json_data={
                    "step": "media_chosen",
                    "result": get_media_json(media)
                },
            )

        if media_type == "audio":
            video = Media(uploaded_by_user=request.user, type="video")
            video_form = MediaForm(instance=video,
                                   user=request.user,
                                   prefix="media-chooser-upload")
            upload_forms = {"audio": uploading_form, "video": video_form}
        else:
            audio = Media(uploaded_by_user=request.user, type="audio")
            audio_form = MediaForm(instance=audio,
                                   user=request.user,
                                   prefix="media-chooser-upload")
            upload_forms = {"audio": audio_form, "video": uploading_form}

    media_files = permission_policy.instances_user_has_any_permission_for(
        request.user, ["change", "delete"])

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks("construct_media_chooser_queryset"):
        media_files = hook(media_files, request)

    searchform = SearchForm()

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

    media_files = media_files.order_by("-created_at")
    paginator, media_files = paginate(request, media_files, per_page=10)

    context = {
        "media_files": media_files,
        "searchform": searchform,
        "collections": collections,
        "uploadforms": upload_forms,
        "is_searching": False,
        "pagination_template": pagination_template,
        "media_type": media_type,
    }
    return render_modal_workflow(
        request,
        "wagtailmedia/chooser/chooser.html",
        None,
        context,
        json_data={"step": "chooser"},
    )
示例#16
0
def chooser(request, media_type=None):
    Media = get_media_model()

    media_files = permission_policy.instances_user_has_any_permission_for(
        request.user, ["change", "delete"])

    # allow hooks to modify the queryset
    for hook in hooks.get_hooks("construct_media_chooser_queryset"):
        media_files = hook(media_files, request)

    if permission_policy.user_has_permission(request.user, "add"):
        MediaForm = get_media_form(Media)
        media_audio = Media(uploaded_by_user=request.user, type="audio")
        media_video = Media(uploaded_by_user=request.user, type="video")

        uploadforms = {
            "audio":
            MediaForm(user=request.user,
                      prefix="media-chooser-upload",
                      instance=media_audio),
            "video":
            MediaForm(user=request.user,
                      prefix="media-chooser-upload",
                      instance=media_video),
        }

        if media_type:
            uploadforms = {media_type: uploadforms[media_type]}
    else:
        uploadforms = {}

    if media_type:
        media_files = media_files.filter(type=media_type)

    if ("q" in request.GET or "p" in request.GET or "tag" in request.GET
            or "collection_id" in request.GET):
        collection_id = request.GET.get("collection_id")
        if collection_id:
            media_files = media_files.filter(collection=collection_id)

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

            media_files = media_files.search(q)
            is_searching = True
        else:
            media_files = media_files.order_by("-created_at")
            is_searching = False
            q = None

            tag_name = request.GET.get("tag")
            if tag_name:
                media_files = media_files.filter(tags__name=tag_name)

        # Pagination
        paginator, media_files = paginate(request, media_files, per_page=10)

        return render(
            request,
            "wagtailmedia/chooser/results.html",
            {
                "media_files": media_files,
                "query_string": q,
                "is_searching": is_searching,
                "pagination_template": pagination_template,
                "media_type": media_type,
            },
        )
    else:
        searchform = SearchForm()

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

        media_files = media_files.order_by("-created_at")
        paginator, media_files = paginate(request, media_files, per_page=10)

    return render_modal_workflow(
        request,
        "wagtailmedia/chooser/chooser.html",
        None,
        {
            "media_files": media_files,
            "searchform": searchform,
            "collections": collections,
            "uploadforms": uploadforms,
            "is_searching": False,
            "pagination_template": pagination_template,
            "popular_tags": popular_tags_for_model(Media),
            "media_type": media_type,
        },
        json_data={
            "step": "chooser",
            "error_label": "Server Error",
            "error_message":
            "Report this error to your webmaster with the following information:",
            "tag_autocomplete_url": reverse("wagtailadmin_tag_autocomplete"),
        },
    )
示例#17
0
 def test_get_overridden_media_form_widgets(self):
     Form = get_media_form(models.Media)
     form = Form()
     self.assertIsInstance(form.fields['tags'].widget, OverridenWidget)
     self.assertIsInstance(form.fields['file'].widget, OverridenWidget)
     self.assertIsInstance(form.fields['thumbnail'].widget, OverridenWidget)
示例#18
0
 def test_get_overridden_media_form(self):
     bases = get_media_form(models.Media).__bases__
     self.assertNotIn(BaseMediaForm, bases)
     self.assertIn(AlternateMediaForm, bases)
示例#19
0
 def test_audio_form_presents_thumbnail(self):
     MediaForm = get_media_form(Media)
     media = Media.objects.create(title="Test media file",
                                  type='audio',
                                  duration=100)
     self.assertIn('thumbnail', MediaForm(instance=media).fields.keys())