def chooser_upload(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == 'POST': document = Document(uploaded_by_user=request.user) form = DocumentForm(request.POST, request.FILES, instance=document, user=request.user) if form.is_valid(): form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return render_modal_workflow( request, None, 'wagtaildocs/chooser/document_chosen.js', {'document_json': get_document_json(document)} ) else: form = DocumentForm(user=request.user) documents = Document.objects.order_by('title') return render_modal_workflow( request, 'wagtaildocs/chooser/chooser.html', 'wagtaildocs/chooser/chooser.js', {'documents': documents, 'uploadform': form} )
def chooser_select(request, image_id): Image = get_image_model() ImageForm = get_image_form(Image, hide_file=True) 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 image.is_editable_by_user(request.user): 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 search_index.insert_or_update_object(image) # several possibilities starting from here, based on the GET params # will_select_format = request.GET.get('select_format') will_select_rendition = request.GET.get('select_rendition') if will_select_format: form = ImageInsertionForm( initial={'alt_text': image.default_alt_text}) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', 'wagtailimages/chooser/select_format.js', {'image': image, 'form': form} ) elif will_select_rendition: form = ImageCropperForm(**get_cropper_settings(request, image)) return render_modal_workflow( request, 'wagtailimages/chooser/select_rendition.html', 'wagtailimages/chooser/select_rendition.js', {'image': image, 'form': form} ) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, 'wagtailimages/chooser/image_chosen.js', {'image_json': get_image_json(image)} ) else: # something was wrong with the submitted data # return JsonResponse({ 'success': False, 'image_id': int(image_id), 'form': render_to_string('wagtailimages/chooser/update.html', { 'image': image, 'form': form, 'additional_params': get_cropper_params(request), }, request=request), })
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, })
def chooser_upload(request): VideoForm = get_video_form(Video) searchform = SearchForm() if request.POST: video = Video(uploaded_by_user=request.user) form = VideoForm(request.POST, request.FILES, instance=video) if form.is_valid(): video.uploaded_by_user = request.user video.save() # Reindex the video to make sure all tags are indexed search_index.insert_or_update_object(video) return render_modal_workflow( request, None, 'wagtailvideos/chooser/video_chosen.js', {'video_json': get_video_json(video)} ) else: form = VideoForm() videos = Video.objects.order_by('title') paginator, videos = paginate(request, videos, per_page=12) return render_modal_workflow( request, 'wagtailvideos/chooser/chooser.html', 'wagtailvideos/chooser/chooser.js', {'videos': videos, 'uploadform': form, 'searchform': searchform} )
def add(request): ImageModel = get_image_model() ImageForm = get_image_form(ImageModel) if request.method == 'POST': image = ImageModel(uploaded_by_user=request.user) form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): # Set image file size image.file_size = image.file.size form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) messages.success(request, _("Image '{0}' added.").format(image.title), buttons=[ messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit')) ]) return redirect('wagtailimages:index') else: messages.error(request, _("The image could not be created due to errors.")) else: form = ImageForm(user=request.user) return render(request, "wagtailimages/images/add.html", { 'form': form, })
def chooser_upload(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == 'POST': document = Document(uploaded_by_user=request.user) form = DocumentForm(request.POST, request.FILES, instance=document, user=request.user) if form.is_valid(): document.file_size = document.file.size form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return render_modal_workflow( request, None, 'wagtaildocs/chooser/document_chosen.js', {'document_json': get_document_json(document)}) else: form = DocumentForm(user=request.user) documents = Document.objects.order_by('title') return render_modal_workflow(request, 'wagtaildocs/chooser/chooser.html', 'wagtaildocs/chooser/chooser.js', { 'documents': documents, 'uploadform': form })
def add(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == 'POST': doc = Document(uploaded_by_user=request.user) form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user) if form.is_valid(): doc.file_size = doc.file.size form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(doc) messages.success(request, _("Document '{0}' added.").format(doc.title), buttons=[ messages.button(reverse('wagtaildocs:edit', args=(doc.id,)), _('Edit')) ]) return redirect('wagtaildocs:index') else: messages.error(request, _("The document could not be saved due to errors.")) else: form = DocumentForm(user=request.user) return render(request, "wagtaildocs/documents/add.html", { 'form': form, })
def chooser_upload(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == 'POST': document = Document(uploaded_by_user=request.user) form = DocumentForm(request.POST, request.FILES, instance=document, user=request.user) if form.is_valid(): document.file_size = document.file.size # Set new document file hash document.file.seek(0) document._set_file_hash(document.file.read()) document.file.seek(0) form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return render_modal_workflow( request, None, None, None, json_data={'step': 'document_chosen', 'result': get_document_result_data(document)} ) else: form = DocumentForm(user=request.user) documents = Document.objects.order_by('title') return render_modal_workflow( request, 'wagtaildocs/chooser/chooser.html', None, {'documents': documents, 'uploadform': form}, json_data=get_chooser_context() )
def chooser_upload(request): FormForm = get_form_form(Form) if request.method == 'POST': form = Form(uploaded_by_user=request.user) form_form = FormForm(request.POST, request.FILES, instance=form, user=request.user) if form_form.is_valid(): form_form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(form) return render_modal_workflow(request, None, 'customforms/chooser/form_chosen.js', {'form_json': get_form_json(form)}) else: form_form = FormForm(user=request.user) forms = Form.objects.order_by('title') return render_modal_workflow(request, 'customforms/chooser/chooser.html', 'customforms/chooser/chooser.js', { 'forms': forms, 'uploadform': form })
def document_chosen(request, document_id): doc = get_object_or_404(get_document_model(), id=document_id) Document = get_document_model() DocumentMultiForm = get_document_multi_form(Document) # handle some updated data if this is a POST if request.POST: if not request.is_ajax(): return http.HttpResponseBadRequest( "Cannot POST to this view without AJAX") form = DocumentMultiForm( request.POST, request.FILES, instance=doc, prefix='doc-' + document_id, user=request.user ) if form.is_valid(): form.save() # Reindex the doc to make sure all tags are indexed search_index.insert_or_update_object(doc) return render_modal_workflow( request, None, 'wagtaildocs/chooser/document_chosen.js', {'document_json': get_document_json(doc)} )
def test_inserts_object(self, backend): obj = models.Book.objects.create(title="Test", publication_date=date(2017, 10, 18), number_of_pages=100) backend().reset_mock() index.insert_or_update_object(obj) backend().add.assert_called_with(obj)
def test_doesnt_insert_unsaved_object(self, backend): obj = models.Book(title="Test", publication_date=date(2017, 10, 18), number_of_pages=100) backend().reset_mock() index.insert_or_update_object(obj) self.assertFalse(backend().add.mock_calls)
def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS("Importing images")) if not options["from_dir"].endswith("/"): options["from_dir"] = options["from_dir"] + "/" for filepath in sorted(glob(options["from_dir"] + "*-90x90.png")): with open(filepath, "rb") as image_file: name = filepath.split("/")[-1][:-10] image = Image(title=name) image.file = ImageFile(file=image_file, name=name + ".png") image.file_size = image.file.size image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) image.save() image.tags.add("illustration") self.stdout.write( self.style.SUCCESS(f"{image.pk},{image.title}")) self.stdout.write(self.style.SUCCESS("Importing images finished"))
def add(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == 'POST': doc = Document(uploaded_by_user=request.user) form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user) if form.is_valid(): doc.file_size = doc.file.size # Set new document file hash doc.file.seek(0) doc._set_file_hash(doc.file.read()) doc.file.seek(0) form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(doc) messages.success(request, _("Document '{0}' added.").format(doc.title), buttons=[ messages.button(reverse('wagtaildocs:edit', args=(doc.id,)), _('Edit')) ]) return redirect('wagtaildocs:index') else: messages.error(request, _("The document could not be saved due to errors.")) else: form = DocumentForm(user=request.user) return render(request, "wagtaildocs/documents/add.html", { 'form': form, })
def chooser_upload(request): VideoForm = get_video_form(Video) searchform = SearchForm() if request.POST: video = Video(uploaded_by_user=request.user) form = VideoForm(request.POST, request.FILES, instance=video) if form.is_valid(): video.uploaded_by_user = request.user video.save() # Reindex the video to make sure all tags are indexed search_index.insert_or_update_object(video) return render_modal_workflow( request, None, json_data={ 'step': 'video_chosen', 'result': get_video_json(video) } ) else: form = VideoForm() videos = Video.objects.order_by('title') paginator = Paginator(videos, per_page=12) page = paginator.get_page(request.GET.get('p')) return render_modal_workflow( request, 'wagtailvideos/chooser/chooser.html', None, template_vars={'videos': page, 'uploadform': form, 'searchform': searchform}, json_data=get_chooser_js_data() )
def add(request): ImageModel = get_image_model() ImageForm = get_image_form(ImageModel) if request.method == 'POST': image = ImageModel(uploaded_by_user=request.user) form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): # Set image file size image.file_size = image.file.size # Set image file hash image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) messages.success(request, _("Image '{0}' added.").format(image.title), buttons=[ messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit')) ]) return redirect('wagtailimages:index') else: messages.error(request, _("The image could not be created due to errors.")) else: form = ImageForm(user=request.user) return TemplateResponse(request, "wagtailimages/images/add.html", { 'form': form, })
def chooser_upload(request): Image = get_image_model() ImageForm = get_image_form(Image) if request.method == 'POST': image = Image(uploaded_by_user=request.user) form = ImageForm( request.POST, request.FILES, instance=image, user=request.user, prefix='image-chooser-upload' ) if form.is_valid(): # Set image file size image.file_size = image.file.size # Set image file hash image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) if request.GET.get('select_format'): form = ImageInsertionForm( initial={'alt_text': image.default_alt_text}, prefix='image-chooser-insertion' ) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', None, {'image': image, 'form': form}, json_data={'step': 'select_format'} ) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, None, None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)} ) else: form = ImageForm(user=request.user, prefix='image-chooser-upload') images = Image.objects.order_by('-created_at') # allow hooks to modify the queryset for hook in hooks.get_hooks('construct_image_chooser_queryset'): images = hook(images, request) paginator = Paginator(images, per_page=12) images = paginator.get_page(request.GET.get('p')) context = get_chooser_context(request) context.update({ 'images': images, 'uploadform': form, }) return render_modal_workflow( request, 'wagtailimages/chooser/chooser.html', None, context, json_data=get_chooser_js_data() )
def chooser_upload(request): Image = get_image_model() ImageForm = get_image_form(Image) if request.method == 'POST': image = Image(uploaded_by_user=request.user) form = ImageForm( request.POST, request.FILES, instance=image, user=request.user, prefix='image-chooser-upload' ) if form.is_valid(): # Set image file size image.file_size = image.file.size # Set image file hash image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) if request.GET.get('select_format'): form = ImageInsertionForm( initial={'alt_text': image.default_alt_text}, prefix='image-chooser-insertion' ) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', None, {'image': image, 'form': form}, json_data={'step': 'select_format'} ) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, None, None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)} ) else: form = ImageForm(user=request.user, prefix='image-chooser-upload') images = Image.objects.order_by('-created_at') # allow hooks to modify the queryset for hook in hooks.get_hooks('construct_image_chooser_queryset'): images = hook(images, request) paginator = Paginator(images, per_page=CHOOSER_PAGE_SIZE) images = paginator.get_page(request.GET.get('p')) context = get_chooser_context(request) context.update({ 'images': images, 'uploadform': form, }) return render_modal_workflow( request, 'wagtailimages/chooser/chooser.html', None, context, json_data=get_chooser_js_data() )
def post_save_signal_handler(instance, update_fields=None, **kwargs): if update_fields is not None: # fetch a fresh copy of instance from the database to ensure # that we're not indexing any of the unsaved data contained in # the fields that were not passed in update_fields instance = type(instance).objects.get(pk=instance.pk) index.insert_or_update_object(instance)
def edit(request, document_id): Document = get_document_model() DocumentForm = get_document_form(Document) doc = get_object_or_404(Document, id=document_id) if not permission_policy.user_has_permission_for_instance(request.user, 'change', doc): return permission_denied(request) if request.method == 'POST': original_file = doc.file form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user) if form.is_valid(): doc = form.save() if 'file' in form.changed_data: # if providing a new document 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) # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(doc) messages.success(request, _("Document '{0}' updated").format(doc.title), buttons=[ messages.button(reverse('wagtaildocs:edit', args=(doc.id,)), _('Edit')) ]) return redirect('wagtaildocs:index') else: messages.error(request, _("The document could not be saved due to errors.")) else: form = DocumentForm(instance=doc, user=request.user) filesize = None # Get file size when there is a file associated with the Document object if doc.file: try: filesize = doc.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 document"), buttons=[messages.button(reverse('wagtaildocs:delete', args=(doc.id,)), _('Delete'))] ) return render(request, "wagtaildocs/documents/edit.html", { 'document': doc, 'filesize': filesize, 'form': form, 'user_can_delete': permission_policy.user_has_permission_for_instance( request.user, 'delete', doc ), })
def edit(request, document_id): Document = get_document_model() DocumentForm = get_document_form(Document) doc = get_object_or_404(Document, id=document_id) if not permission_policy.user_has_permission_for_instance(request.user, 'change', doc): return permission_denied(request) if request.method == 'POST': original_file = doc.file form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user) if form.is_valid(): doc = form.save() if 'file' in form.changed_data: doc.file_size = doc.file.size # if providing a new document 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) # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(doc) messages.success(request, _("Document '{0}' updated").format(doc.title), buttons=[ messages.button(reverse('wagtaildocs:edit', args=(doc.id,)), _('Edit')) ]) return redirect('wagtaildocs:index') else: messages.error(request, _("The document could not be saved due to errors.")) else: form = DocumentForm(instance=doc, user=request.user) try: local_path = doc.file.path except NotImplementedError: # Document is hosted externally (eg, S3) local_path = None if local_path: # Give error if document file doesn't exist if not os.path.isfile(local_path): messages.error( request, _("The file could not be found. Please change the source or delete the document"), buttons=[messages.button(reverse('wagtaildocs:delete', args=(doc.id,)), _('Delete'))] ) return render(request, "wagtaildocs/documents/edit.html", { 'document': doc, 'filesize': doc.get_file_size(), 'form': form, 'user_can_delete': permission_policy.user_has_permission_for_instance( request.user, 'delete', doc ), })
def create_image(self, image_file, title, filename, tag): image = Image(title=title) image.file = ImageFile(file=image_file, name=filename) image.file_size = image.file.size image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) image.save() image.tags.add(tag) return image
def chooser_upload(request): Image = get_image_model() ImageForm = get_image_form(Image) if request.method == 'POST': image = Image(uploaded_by_user=request.user) form = ImageForm( request.POST, request.FILES, instance=image, user=request.user, prefix='image-chooser-upload' ) if form.is_valid(): # Set image file size image.file_size = image.file.size # Set image file hash image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) if request.GET.get('select_format'): form = ImageInsertionForm( initial={'alt_text': image.default_alt_text}, prefix='image-chooser-insertion' ) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', None, {'image': image, 'form': form}, json_data={'step': 'select_format'} ) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, None, None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)} ) else: form = ImageForm(user=request.user, prefix='image-chooser-upload') upload_form_html = render_to_string('wagtailimages/chooser/upload_form.html', { 'form': form, 'will_select_format': request.GET.get('select_format'), }, request) return render_modal_workflow( request, None, None, None, json_data={ 'step': 'reshow_upload_form', 'htmlFragment': upload_form_html } )
def document_chooser_upload(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == "POST": document = Document(uploaded_by_user=request.user) form = DocumentForm( request.POST, request.FILES, instance=document, user=request.user, prefix="document-chooser-upload", ) if form.is_valid(): document.file_size = document.file.size # Set new document file hash document.file.seek(0) document._set_file_hash(document.file.read()) document.file.seek(0) form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return render_modal_workflow( request, None, None, None, json_data={ "step": "document_chosen", "result": get_document_result_data(document), }, ) else: form = DocumentForm(user=request.user, prefix="document-chooser-upload") documents = Document.objects.order_by("title") return render_modal_workflow( request, "non_admin_draftail/document/chooser.html", None, { "documents": documents, "uploadform": form }, json_data=get_chooser_context(), )
def test_converts_to_specific_page(self, backend): root_page = Page.objects.get(id=1) page = root_page.add_child(instance=SimplePage(title="test", slug="test", content="test")) # Convert page into a generic "Page" object and add it into the index unspecific_page = page.page_ptr backend().reset_mock() index.insert_or_update_object(unspecific_page) # It should be automatically converted back to the specific version backend().add.assert_called_with(page)
def test_catches_index_error(self, backend): obj = models.Book.objects.create(title="Test", publication_date=date(2017, 10, 18), number_of_pages=100) backend().add.side_effect = ValueError("Test") backend().reset_mock() with self.assertLogs('wagtail.search.index', level='ERROR') as cm: index.insert_or_update_object(obj) self.assertEqual(len(cm.output), 1) self.assertIn("Exception raised while adding <Book: Test> into the 'default' search backend", cm.output[0]) self.assertIn("Traceback (most recent call last):", cm.output[0]) self.assertIn("ValueError: Test", cm.output[0])
def chooser_upload(request): EmbedVideo = get_embed_video_model() EmbedVideoForm = get_embed_video_form(EmbedVideo) searchform = SearchForm() if request.POST: embed_video = EmbedVideo(uploaded_by_user=request.user) form = EmbedVideoForm(request.POST, request.FILES, instance=embed_video, user=request.user) if form.is_valid(): form.save() # Reindex the video to make sure all tags are indexed search_index.insert_or_update_object(embed_video) if request.GET.get('select_format'): form = EmbedVideoInsertionForm( initial={'alt_text': embed_video.default_alt_text}) return render_modal_workflow( request, 'wagtail_embed_videos/chooser/select_format.html', 'wagtail_embed_videos/chooser/select_format.js', { 'embed_video': embed_video, 'form': form }) # not specifying a format; return the embed video details now else: json_data = get_embed_video_json(embed_video) json_data['step'] = 'embed_video_chosen' return render_modal_workflow( request, None, None, #'wagtail_embed_videos/chooser/embed_video_chosen.js', json_data=json_data) else: form = EmbedVideoForm(user=request.user) embed_videos = EmbedVideo.objects.order_by('-created_at') paginator, images = paginate(request, embed_videos, per_page=12) return render_modal_workflow(request, 'wagtail_embed_videos/chooser/chooser.html', None, { 'embed_videos': embed_videos, 'uploadform': form, 'searchform': searchform })
def test_converts_to_specific_page(self, backend): root_page = Page.objects.get(id=1) page = root_page.add_child( instance=SimplePage(title="test", slug="test", content="test")) # Convert page into a generic "Page" object and add it into the index unspecific_page = page.page_ptr backend().reset_mock() index.insert_or_update_object(unspecific_page) # It should be automatically converted back to the specific version backend().add.assert_called_with(page)
def chooser_upload(request): Image = get_image_model() ImageForm = get_image_form(Image) if request.method == 'POST': image = Image(uploaded_by_user=request.user) form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) if request.GET.get('select_format'): form = ImageInsertionForm( initial={'alt_text': image.default_alt_text}) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', 'wagtailimages/chooser/select_format.js', { 'image': image, 'form': form }) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, 'wagtailimages/chooser/image_chosen.js', {'image_json': get_image_json(image)}) else: form = ImageForm(user=request.user) images = Image.objects.order_by('-created_at') # allow hooks to modify the queryset for hook in hooks.get_hooks('construct_image_chooser_queryset'): images = hook(images, request) paginator, images = paginate(request, images, per_page=12) context = get_chooser_context(request) context.update({ 'images': images, 'uploadform': form, }) return render_modal_workflow(request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js', context)
def save_form(self, form): document = form.instance document.file_size = document.file.size # Set new document file hash document.file.seek(0) document._set_file_hash(document.file.read()) document.file.seek(0) form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return document
def chooser_upload(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == 'POST': document = Document(uploaded_by_user=request.user) form = DocumentForm(request.POST, request.FILES, instance=document, user=request.user, prefix='document-chooser-upload') if form.is_valid(): document.file_size = document.file.size # Set new document file hash document.file.seek(0) document._set_file_hash(document.file.read()) document.file.seek(0) form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return render_modal_workflow(request, None, None, None, json_data={ 'step': 'document_chosen', 'result': get_document_result_data(document) }) else: form = DocumentForm(user=request.user, prefix='document-chooser-upload') documents = Document.objects.order_by('title') return render_modal_workflow(request, 'wagtaildocs/chooser/chooser.html', None, { 'documents': documents, 'uploadform': form }, json_data=get_chooser_context())
def update_index(arguments): # the spooler is forked so the db connection might be closed if not connection.is_usable(): connection.close() category_id = arguments.get("category_id") product_id = arguments.get("product_id") if category_id is not None: products = ProductProxy.objects.filter(categories__id=category_id) for product in products: index.insert_or_update_object(product) if product_id is not None: product = ProductProxy.objects.get(pk=product_id) index.insert_or_update_object(product)
def test_catches_index_error(self, backend): obj = models.Book.objects.create(title="Test", publication_date=date(2017, 10, 18), number_of_pages=100) backend().add.side_effect = ValueError("Test") backend().reset_mock() with self.assertLogs('wagtail.search.index', level='ERROR') as cm: index.insert_or_update_object(obj) self.assertEqual(len(cm.output), 1) self.assertIn( "Exception raised while adding <Book: Test> into the 'default' search backend", cm.output[0]) self.assertIn("Traceback (most recent call last):", cm.output[0]) self.assertIn("ValueError: Test", cm.output[0])
def chooser_upload(request): Image = get_image_model() ImageForm = get_image_form(Image) searchform = SearchForm() if request.method == 'POST': image = Image(uploaded_by_user=request.user) form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): # Set image file size image.file_size = image.file.size # Set image file hash image.file.seek(0) image._set_file_hash(image.file.read()) form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) if request.GET.get('select_format'): form = ImageInsertionForm(initial={'alt_text': image.default_alt_text}) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', None, {'image': image, 'form': form}, json_data={'step': 'select_format'} ) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, None, None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)} ) else: form = ImageForm(user=request.user) images = Image.objects.order_by('-created_at') paginator, images = paginate(request, images, per_page=12) return render_modal_workflow( request, 'wagtailimages/chooser/chooser.html', None, {'images': images, 'uploadform': form, 'searchform': searchform}, json_data=get_chooser_context() )
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())
def chooser_upload(request): Image = get_image_model() ImageForm = get_image_form(Image) searchform = SearchForm() if request.method == 'POST': image = Image(uploaded_by_user=request.user) form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): # Set image file size image.file_size = image.file.size # Set image file hash image.file.seek(0) image._set_file_hash(image.file.read()) form.save() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) if request.GET.get('select_format'): form = ImageInsertionForm(initial={'alt_text': image.default_alt_text}) return render_modal_workflow( request, 'wagtailimages/chooser/select_format.html', 'wagtailimages/chooser/select_format.js', {'image': image, 'form': form} ) else: # not specifying a format; return the image details now return render_modal_workflow( request, None, 'wagtailimages/chooser/image_chosen.js', {'image_json': get_image_json(image)} ) else: form = ImageForm(user=request.user) images = Image.objects.order_by('-created_at') paginator, images = paginate(request, images, per_page=12) return render_modal_workflow( request, 'wagtailimages/chooser/chooser.html', 'wagtailimages/chooser/chooser.js', {'images': images, 'uploadform': form, 'searchform': searchform} )
def save(self, commit=True): if "file" in self.changed_data: self.instance._set_image_file_metadata() super().save(commit=commit) if commit: if "file" in self.changed_data and self.original_file: # if providing a new image file, delete the old one and all renditions. # NB Doing this via original_file.delete() clears the file field, # which definitely isn't what we want... self.original_file.storage.delete(self.original_file.name) self.instance.renditions.all().delete() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(self.instance) return self.instance
def chooser_upload(request): Document = get_document_model() DocumentForm = get_document_form(Document) if request.method == "POST": document = Document(uploaded_by_user=request.user) form = DocumentForm( request.POST, request.FILES, instance=document, user=request.user, prefix="document-chooser-upload", ) if form.is_valid(): document.file_size = document.file.size # Set new document file hash document.file.seek(0) document._set_file_hash(document.file.read()) document.file.seek(0) form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(document) return get_document_chosen_response(request, document) else: form = DocumentForm(user=request.user, prefix="document-chooser-upload") return render_modal_workflow( request, None, None, None, json_data={ "step": "reshow_upload_form", "htmlFragment": render_to_string("wagtaildocs/chooser/upload_form.html", {"form": form}, request), }, )
def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS("Importing images")) with open(options["speakers_csv"], "r") as file: for row in DictReader(file): if not row["filename"]: self.stdout.write( self.style.WARNING( f"====> skipping {row['post_name']}, {row['post_title']}" )) continue image_path = os.path.join(options["from_dir"], row["filename"]) with open(image_path, "rb") as image_file: image = Image(title=row["post_title"]) if row["filename"].lower().endswith(".jpg") or row[ "filename"].lower().endswith(".jpeg"): image_filename = f"{row['first_name']} {row['last_name']}.jpg" elif row["filename"].lower().endswith(".png"): image_filename = f"{row['first_name']} {row['last_name']}.png" else: raise ValueError("Unknown file format") image.file = ImageFile(file=image_file, name=image_filename) image.file_size = image.file.size image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) image.save() image.tags.add("speaker") speaker = Speaker.objects.get(wordpress_id=row["ID"]) speaker.photo = image speaker.save() self.stdout.write( self.style.SUCCESS(f"{image.pk},{image.title}")) self.stdout.write(self.style.SUCCESS("Importing images finished"))
def edit(request, image_id): Image = get_image_model() ImageForm = get_image_form(Image) image = get_object_or_404(Image, id=image_id) if not permission_policy.user_has_permission_for_instance( request.user, 'change', image): return permission_denied(request) if request.method == 'POST': original_file = image.file form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): if 'file' in form.changed_data: # Set new image file size image.file_size = image.file.size # Set new image file hash image.file.seek(0) image._set_file_hash(image.file.read()) image.file.seek(0) form.save() if 'file' in form.changed_data: # if providing a new image file, delete the old one and all renditions. # NB Doing this via original_file.delete() clears the file field, # which definitely isn't what we want... original_file.storage.delete(original_file.name) image.renditions.all().delete() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) messages.success(request, _("Image '{0}' updated.").format(image.title), buttons=[ messages.button( reverse('wagtailimages:edit', args=(image.id, )), _('Edit again')) ]) return redirect('wagtailimages:index') else: messages.error(request, _("The image could not be saved due to errors.")) else: form = ImageForm(instance=image, user=request.user) # Check if we should enable the frontend url generator try: reverse('wagtailimages_serve', args=('foo', '1', 'bar')) url_generator_enabled = True except NoReverseMatch: url_generator_enabled = False if image.is_stored_locally(): # Give error if image file doesn't exist if not os.path.isfile(image.file.path): messages.error( request, _("The source image file could not be found. Please change the source or delete the image." ).format(image.title), buttons=[ messages.button( reverse('wagtailimages:delete', args=(image.id, )), _('Delete')) ]) try: filesize = image.get_file_size() except SourceImageIOError: filesize = None return render( request, "wagtailimages/images/edit.html", { 'image': image, 'form': form, 'url_generator_enabled': url_generator_enabled, 'filesize': filesize, 'user_can_delete': permission_policy.user_has_permission_for_instance( request.user, 'delete', image), })
def edit(request, image_id): Image = get_image_model() ImageForm = get_image_form(Image) image = get_object_or_404(Image, id=image_id) if not permission_policy.user_has_permission_for_instance(request.user, 'change', image): return permission_denied(request) if request.method == 'POST': original_file = image.file form = ImageForm(request.POST, request.FILES, instance=image, user=request.user) if form.is_valid(): if 'file' in form.changed_data: # Set new image file size image.file_size = image.file.size form.save() if 'file' in form.changed_data: # if providing a new image file, delete the old one and all renditions. # NB Doing this via original_file.delete() clears the file field, # which definitely isn't what we want... original_file.storage.delete(original_file.name) image.renditions.all().delete() # Reindex the image to make sure all tags are indexed search_index.insert_or_update_object(image) messages.success(request, _("Image '{0}' updated.").format(image.title), buttons=[ messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit again')) ]) return redirect('wagtailimages:index') else: messages.error(request, _("The image could not be saved due to errors.")) else: form = ImageForm(instance=image, user=request.user) # Check if we should enable the frontend url generator try: reverse('wagtailimages_serve', args=('foo', '1', 'bar')) url_generator_enabled = True except NoReverseMatch: url_generator_enabled = False if image.is_stored_locally(): # Give error if image file doesn't exist if not os.path.isfile(image.file.path): messages.error(request, _( "The source image file could not be found. Please change the source or delete the image." ).format(image.title), buttons=[ messages.button(reverse('wagtailimages:delete', args=(image.id,)), _('Delete')) ]) return render(request, "wagtailimages/images/edit.html", { 'image': image, 'form': form, 'url_generator_enabled': url_generator_enabled, 'filesize': image.get_file_size(), 'user_can_delete': permission_policy.user_has_permission_for_instance( request.user, 'delete', image ), })