From 7fe208f5d3d03f58debf0be5c4e967c8be5bf3e7 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Wed, 2 Sep 2020 13:14:36 +0200 Subject: [PATCH] Move copy buttons to python and display in edit form --- attachments/admin.py | 24 +++++++++++++++++-- attachments/static/attachments/js/copy_url.js | 23 +++++------------- 2 files changed, 28 insertions(+), 19 deletions(-) diff --git a/attachments/admin.py b/attachments/admin.py index 2d69f13..ccc189d 100644 --- a/attachments/admin.py +++ b/attachments/admin.py @@ -1,5 +1,6 @@ from django.contrib import admin from django.contrib.admin import register +from django.utils.html import format_html from attachments.models import Attachment @@ -14,16 +15,35 @@ class AttachmentAdmin(admin.ModelAdmin): "processed_file_url", ] list_display_links = ["description"] + fields = [ + "description", + "original_file", + "original_file_url", + "processed_file", + "processed_file_url", + ] + readonly_fields = [ + "original_file_url", + "processed_file_url", + ] class Media: js = ["attachments/js/copy_url.js"] def processed_file_url(self, instance): if instance.processed_file: - return instance.processed_file.url + return format_html( + '{} 📋', + instance.processed_file.url, + instance.processed_file.url, + ) return "" def original_file_url(self, instance): if instance.original_file: - return instance.original_file.url + return format_html( + '{} 📋', + instance.original_file.url, + instance.original_file.url, + ) return "" diff --git a/attachments/static/attachments/js/copy_url.js b/attachments/static/attachments/js/copy_url.js index 22a6ea6..22428c5 100644 --- a/attachments/static/attachments/js/copy_url.js +++ b/attachments/static/attachments/js/copy_url.js @@ -1,24 +1,13 @@ -function copy(data) { - navigator.clipboard.writeText(data.data).then(() => { +function copy(event) { + const text = event.target.dataset.toCopy; + navigator.clipboard.writeText(text).then(() => { console.log("Copied"); }) } $(document).ready(function() { - const $ = django.jQuery; - const fileUrls = $('td.field-processed_file_url, td.field-original_file_url'); - let id = 0; - for (let fileUrl of fileUrls) { - fileUrl = $(fileUrl); - const existingText = fileUrl.text().trim(); - if (!existingText) { - continue; - } - const buttonId = `copy-button-${id}`; - const copyButton = `📋`; - let innerHTML = `${existingText} ${copyButton}`; - fileUrl.html(innerHTML); - $(`#${buttonId}`).on("click", null, existingText, copy); - id++; + const buttons = document.querySelectorAll(".copy-button"); + for (const button of buttons) { + button.addEventListener("click", copy); } });