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, })
def add(request): EmbedVideoModel = get_embed_video_model() EmbedVideoForm = get_embed_video_form(EmbedVideoModel) if request.POST: embed_video = EmbedVideoModel(uploaded_by_user=request.user) form = EmbedVideoForm(request.POST, request.FILES, instance=embed_video) if form.is_valid(): form.save() # Reindex the embed video to make sure all tags are indexed for backend in get_search_backends(): backend.add(embed_video) messages.success(request, _("Video '{0}' added.").format(embed_video.title), buttons=[ messages.button(reverse('wagtail_embed_videos_edit_embed_video', args=(embed_video.id,)), _('Edit')) ]) return redirect('wagtail_embed_videos_index') else: messages.error(request, _("The video could not be created due to errors.")) else: form = EmbedVideoForm() return render(request, "wagtail_embed_videos/embed_videos/add.html", { 'form': form, })
def edit(request, video_id, callback=None): Video = get_video_model() VideoForm = get_video_edit_form(Video) video = get_object_or_404(Video, id=video_id) if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") form = VideoForm( request.POST, request.FILES, instance=video, prefix='video-' + video_id ) if form.is_valid(): form.save() # Reindex the video to make sure all tags are indexed for backend in get_search_backends(): backend.add(video) return JsonResponse({ 'success': True, 'video_id': int(video_id), }) else: return JsonResponse({ 'success': False, 'video_id': int(video_id), 'form': render_to_string('wagtailvideos/multiple/edit_form.html', { 'video': video, 'form': form, }, request=request), })
def edit(request, embed_video_id): EmbedVideo = get_embed_video_model() EmbedVideoForm = get_embed_video_form(EmbedVideo) embed_video = get_object_or_404(EmbedVideo, id=embed_video_id) if not embed_video.is_editable_by_user(request.user): raise PermissionDenied if request.POST: form = EmbedVideoForm(request.POST, request.FILES, instance=embed_video) if form.is_valid(): form.save() # Reindex the embed_video to make sure all tags are indexed for backend in get_search_backends(): backend.add(embed_video) messages.success(request, _("Video '{0}' updated.").format(embed_video.title), buttons=[ messages.button(reverse('wagtail_embed_videos_edit_embed_video', args=(embed_video.id,)), _('Edit again')) ]) return redirect('wagtail_embed_videos_index') else: messages.error(request, _("The video could not be saved due to errors.")) else: form = EmbedVideoForm(instance=embed_video) return render(request, "wagtail_embed_videos/embed_videos/edit.html", { 'embed_video': embed_video, 'form': form, })
def add(request): VideoForm = get_video_form(Video) if request.POST: video = Video(uploaded_by_user=request.user) form = VideoForm(request.POST, request.FILES, instance=video, user=request.user) if form.is_valid(): # Save video = form.save(commit=False) video.file_size = video.file.size video.save() # Success! Send back an edit form for backend in get_search_backends(): backend.add(video) messages.success(request, _("Video '{0}' added.").format(video.title), buttons=[ messages.button(reverse('wagtailvideos:edit', args=(video.id,)), _('Edit')) ]) return redirect('wagtailvideos:index') else: messages.error(request, _("The video could not be created due to errors.")) else: form = VideoForm(user=request.user) return render(request, "wagtailvideos/videos/add.html", { 'form': form, })
def add(request): Video = get_video_model() VideoForm = get_video_form(Video) if request.POST: video = Video(uploaded_by_user=request.user) form = VideoForm(request.POST, request.FILES, instance=video, user=request.user) if form.is_valid(): form.save() # Reindex the video entry to make sure all tags are indexed for backend in get_search_backends(): backend.add(video) messages.success(request, _("Video file '{0}' added.").format(video.title), buttons=[ messages.button(reverse('wagtail_video:edit', args=(video.id,)), _('Edit')) ]) return redirect('wagtail_video:index') else: messages.error(request, _("The video file could not be saved due to errors.")) else: video = Video(uploaded_by_user=request.user) form = VideoForm(user=request.user, instance=video) return render(request, "wagtail_video/video/add.html", { 'form': form, })
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 ), })
def edit(request, video_id): Video = get_video_model() VideoForm = get_video_form(Video) video = get_object_or_404(Video, id=video_id) if request.POST: original_file = video.file form = VideoForm(request.POST, request.FILES, instance=video) if form.is_valid(): if 'file' in form.changed_data: # if providing a new video 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) # Set new video file size video.file_size = video.file.size video = form.save() video.save() # Reindex the video to make sure all tags are indexed for backend in get_search_backends(): backend.add(video) messages.success(request, _("Video '{0}' updated.").format(video.title)) else: messages.error(request, _("The video could not be saved due to errors.")) else: form = VideoForm(instance=video) if not video._meta.get_field('file').storage.exists(video.file.name): # Give error if video file doesn't exist messages.error(request, _( "The source video file could not be found. Please change the source or delete the video." ).format(video.title), buttons=[ messages.button(reverse('wagtailvideos:delete', args=(video.id,)), _('Delete')) ]) if is_modeladmin_installed(): url_helper = AdminURLHelper(Video.get_track_listing_model()) if hasattr(video, 'track_listing'): action_url = url_helper.get_action_url('edit', instance_pk=video.track_listing.pk) else: action_url = url_helper.create_url else: action_url = '' return render(request, "wagtailvideos/videos/edit.html", { 'video': video, 'form': form, 'filesize': video.get_file_size(), 'can_transcode': ffmpeg.installed(), 'transcodes': video.transcodes.all(), 'transcode_form': VideoTranscodeAdminForm(video=video), 'tracks_action_url': action_url, 'user_can_delete': permission_policy.user_has_permission_for_instance(request.user, 'delete', video) })
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'})
def edit(request, image_id, callback=None): Image = get_image_model() ImageForm = get_image_edit_form(Image) image = get_object_or_404(Image, id=image_id) if not permission_policy.user_has_permission_for_instance( request.user, "change", image): raise PermissionDenied form = ImageForm( request.POST, request.FILES, instance=image, prefix="image-" + str(image_id), user=request.user, ) 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 JsonResponse({ "success": True, "image_id": int(image_id), }) else: return JsonResponse({ "success": False, "image_id": int(image_id), "form": render_to_string( "wagtail_image_import/edit_form.html", { "image": image, "edit_action": reverse("wagtail_image_import:edit", args=(image_id, )), "delete_action": reverse("wagtailimages:delete_multiple", args=(image_id, )), "form": form, }, request=request, ), })
def post_save_signal_handler(instance, **kwargs): update_fields = kwargs.get('update_fields') social_fields = frozenset(('cached_facebook_count', 'cached_last_updated')) if update_fields == social_fields: return # Don't update the search index if we are just updating facebook page counts indexed_instance = get_indexed_instance(instance) if indexed_instance: for backend in get_search_backends(with_auto_update=True): backend.add(indexed_instance)
def create_from_uploaded_image(request, uploaded_image_id): Image = get_image_model() ImageForm = get_image_edit_form(Image) uploaded_image = get_object_or_404(UploadedImage, id=uploaded_image_id) if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") if uploaded_image.uploaded_by_user != request.user: raise PermissionDenied image = Image() form = ImageForm( request.POST, request.FILES, instance=image, prefix='uploaded-image-%d' % uploaded_image_id, user=request.user ) if form.is_valid(): # assign the file content from uploaded_image to the image object, to ensure it gets saved to # Image's storage image.file.save(os.path.basename(uploaded_image.file.name), uploaded_image.file.file, save=False) image.uploaded_by_user = request.user image.file_size = image.file.size image.file.open() image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() uploaded_image.file.delete() uploaded_image.delete() # Reindex the image to make sure all tags are indexed for backend in get_search_backends(): backend.add(image) return JsonResponse({ 'success': True, 'image_id': image.id, }) else: return JsonResponse({ 'success': False, 'form': render_to_string('wagtailimages/multiple/edit_form.html', { 'uploaded_image': uploaded_image, 'edit_action': reverse('wagtailimages:create_multiple_from_uploaded_image', args=(uploaded_image.id,)), 'delete_action': reverse('wagtailimages:delete_upload_multiple', args=(uploaded_image.id,)), 'form': form, }, request=request), })
def chooser_upload(request): Video = get_video_model() VideoForm = get_video_form(Video) if request.POST: video = Video(uploaded_by_user=request.user) form = VideoForm(request.POST, request.FILES, instance=video, user=request.user) if form.is_valid(): form.save() # Reindex the video entry to make sure all tags are indexed for backend in get_search_backends(): backend.add(video) return render_modal_workflow(request, None, None, None, json_data={ 'step': 'video_chosen', 'result': get_video_result_data(video) }) else: video = Video(uploaded_by_user=request.user) form = VideoForm(user=request.user, instance=video) video_files = Video.objects.order_by('-created_at') paginator = Paginator(video_files, per_page=10) video_files = paginator.get_page(request.GET.get('p')) context = { 'video_files': video_files, 'searchform': SearchForm(), 'is_searching': False, 'can_add': True, 'uploadform': form, 'popular_tags': popular_tags_for_model(Video), } return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html', None, context, json_data={ 'step': 'chooser', })
def edit(request, image_id, callback=None): Image = get_image_model() ImageForm = get_image_edit_form(Image) 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 permission_policy.user_has_permission_for_instance( request.user, 'change', image): raise PermissionDenied form = ImageForm(request.POST, request.FILES, instance=image, prefix='image-%d' % image_id, user=request.user) 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 JsonResponse({ 'success': True, 'image_id': int(image_id), }) else: return JsonResponse({ 'success': False, 'image_id': int(image_id), 'form': render_to_string('wagtailimages/multiple/edit_form.html', { 'image': image, 'edit_action': reverse('wagtailimages:edit_multiple', args=(image_id, )), 'delete_action': reverse('wagtailimages:delete_multiple', args=(image_id, )), 'form': form, }, request=request), })
def save_object(self, form): # assign the file content from uploaded_image to the image object, to ensure it gets saved to # Image's storage self.object.file.save(os.path.basename(self.upload.file.name), self.upload.file.file, save=False) self.object.uploaded_by_user = self.request.user self.object.file_size = self.object.file.size self.object.file.open() self.object.file.seek(0) self.object._set_file_hash(self.object.file.read()) self.object.file.seek(0) form.save() # Reindex the image to make sure all tags are indexed for backend in get_search_backends(): backend.add(self.object)
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()
def edit(request, doc_id, callback=None): Document = get_document_model() DocumentMultiForm = get_document_multi_form(Document) doc = get_object_or_404(Document, id=doc_id) if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") if not permission_policy.user_has_permission_for_instance( request.user, 'change', doc): raise PermissionDenied form = DocumentMultiForm(request.POST, request.FILES, instance=doc, prefix='doc-' + doc_id, user=request.user) if form.is_valid(): form.save() # Reindex the doc to make sure all tags are indexed for backend in get_search_backends(): backend.add(doc) return JsonResponse({ 'success': True, 'doc_id': int(doc_id), }) else: return JsonResponse({ 'success': False, 'doc_id': int(doc_id), 'form': render_to_string('wagtaildocs/multiple/edit_form.html', { 'doc': doc, 'form': form, }, request=request), })
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, }, )
def edit(request, image_id, callback=None): Image = get_image_model() ImageForm = get_image_edit_form(Image) 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 permission_policy.user_has_permission_for_instance(request.user, 'change', image): raise PermissionDenied form = ImageForm( request.POST, request.FILES, instance=image, prefix='image-' + image_id, user=request.user ) 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 JsonResponse({ 'success': True, 'image_id': int(image_id), }) else: return JsonResponse({ 'success': False, 'image_id': int(image_id), 'form': render_to_string('wagtailimages/multiple/edit_form.html', { 'image': image, 'form': form, }, request=request), })
def edit(request, doc_id, callback=None): Document = get_document_model() DocumentMultiForm = get_document_multi_form(Document) doc = get_object_or_404(Document, id=doc_id) if not request.is_ajax(): return HttpResponseBadRequest("Cannot POST to this view without AJAX") if not permission_policy.user_has_permission_for_instance(request.user, 'change', doc): raise PermissionDenied form = DocumentMultiForm( request.POST, request.FILES, instance=doc, prefix='doc-' + doc_id, user=request.user ) if form.is_valid(): form.save() # Reindex the doc to make sure all tags are indexed for backend in get_search_backends(): backend.add(doc) return JsonResponse({ 'success': True, 'doc_id': int(doc_id), }) else: return JsonResponse({ 'success': False, 'doc_id': int(doc_id), 'form': render_to_string('wagtaildocs/multiple/edit_form.html', { 'doc': doc, 'form': form, }, request=request), })
def save_object(self, form): form.save() # Reindex the image to make sure all tags are indexed for backend in get_search_backends(): backend.add(self.object)
def test_get_search_backends_with_auto_update(self): backends = list(get_search_backends(with_auto_update=True)) # Auto update is the default self.assertEqual(len(backends), 1)
def test_get_search_backends_with_no_default_defined(self): backends = list(get_search_backends()) self.assertEqual(len(backends), 1) self.assertIsInstance(backends[0], DatabaseSearchBackend)
def test_get_search_backends_multiple(self): backends = list(get_search_backends()) self.assertEqual(len(backends), 2)
def edit(request, video_id): Video = get_video_model() VideoForm = get_video_form(Video) video = get_object_or_404(Video, id=video_id) if not permission_policy.user_has_permission_for_instance(request.user, 'change', video): return permission_denied(request) if request.POST: original_file = video.mp4 form = VideoForm(request.POST, request.FILES, instance=video, user=request.user) if form.is_valid(): if 'file' in form.changed_data: # if providing a new video 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) video = form.save() # Reindex the video entry to make sure all tags are indexed for backend in get_search_backends(): backend.add(video) messages.success(request, _("Video file '{0}' updated").format(video.title), buttons=[ messages.button(reverse('wagtail_video:edit', args=(video.id,)), _('Edit')) ]) return redirect('wagtail_video:index') else: messages.error(request, _("The video could not be saved due to errors.")) else: form = VideoForm(instance=video, user=request.user) filesize = None # Get file size when there is a file associated with the Video object if video.mp4: try: filesize = video.mp4.size except OSError: # File doesn't exist pass if video.ogg: try: filesize = video.ogg.size except OSError: # File doesn't exist pass if video.webm: try: filesize = video.webm.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 video file"), buttons=[messages.button(reverse('wagtail_video:delete', args=(video.id,)), _('Delete'))] ) return render(request, "wagtail_video/video/edit.html", { 'video': video, 'filesize': filesize, 'form': form, 'user_can_delete': permission_policy.user_has_permission_for_instance( request.user, 'delete', video ), })
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"}, )
def test_get_search_backends_without_auto_update_disabled(self): backends = list(get_search_backends()) self.assertEqual(len(backends), 1)
def test_get_search_backends_with_no_default_defined(self): backends = list(get_search_backends()) self.assertEqual(len(backends), 1) if not issubclass(type(backends[0]), BaseSearchBackend): self.fail()
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, })
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), })
def create_from_uploaded_image(request, uploaded_image_id): Image = get_image_model() ImageForm = get_image_edit_form(Image) uploaded_image = get_object_or_404(UploadedImage, id=uploaded_image_id) if uploaded_image.uploaded_by_user != request.user: raise PermissionDenied image = Image() form = ImageForm( request.POST, request.FILES, instance=image, prefix="uploaded-image-" + str(uploaded_image_id), user=request.user, ) if form.is_valid(): # assign the file content from uploaded_image to the image object, to ensure it gets saved to # Image's storage image.file.save( os.path.basename(uploaded_image.file.name), uploaded_image.file.file, save=False, ) image.uploaded_by_user = request.user image.file_size = image.file.size image.file.open() image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() uploaded_image.file.delete() uploaded_image.delete() drive_id = request.POST.get("drive_id") if drive_id: DriveIDMapping.objects.update_or_create( image=image, defaults={"drive_id": drive_id}) # Reindex the image to make sure all tags are indexed for backend in get_search_backends(): backend.add(image) return JsonResponse({ "success": True, "image_id": image.id, }) else: return JsonResponse({ "success": False, "edit_action": reverse( "wagtail_image_import:create_from_uploaded_image", args=(uploaded_image.id, ), ), "delete_action": reverse("wagtailimages:delete_upload_multiple", args=(uploaded_image.id, )), "form": render_to_string( "wagtail_image_import/edit_form.html", { "uploaded_image": uploaded_image, "form": form, }, request=request, ), })
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), })