Move copy buttons to python and display in edit form

This commit is contained in:
Gabriel Augendre 2020-09-02 13:14:36 +02:00
parent 049fcb2dce
commit 7fe208f5d3
No known key found for this signature in database
GPG key ID: 1E693F4CE4AEE7B4
2 changed files with 28 additions and 19 deletions

View file

@ -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(
'{} <a class="copy-button" data-to-copy="{}" href="#">&#128203;</a>',
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(
'{} <a class="copy-button" data-to-copy="{}" href="#">&#128203;</a>',
instance.original_file.url,
instance.original_file.url,
)
return ""

View file

@ -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 = `<a class="copy-button" id="${buttonId}" href="#">&#128203;</a>`;
let innerHTML = `<span>${existingText}</span> ${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);
}
});