X
X
xSkyFoXx2015-08-15 14:53:03
Django
xSkyFoXx, 2015-08-15 14:53:03

How to add "Copy to clipboard" button in django admin?

Tell me, please, what is the easiest way to add a link or a button "Copy to clipboard" the contents of this field to a specific field in django-admin?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Filimonov, 2015-08-17
@DmitryPhilimonov

Why is this button needed, if you can ctrl + a and ctrl + c? After all, it is a crutch. Write better about it, for example, in help_text , if necessary, in a couple of places, or even in the template in bold letters.
But if you still have a desire ... The easiest way is to search here . If there is nothing there, then "complex" remains.
I understand that we are talking about the editing page. You need to make a separate application with a JS script and / or a custom template, as well as make a class / mixin for the admin panel in order to conveniently do something in the style:

class YourModelAdmin(ClipboardMixin, admin.ModelAdmin):
    clipboard_fields = ('clipboardable_field',)

You can pass the required fields to the template in different ways:
I see the second option as correct, and we will implement it.
class ClipboardMixin(object):
    #change_form_template = 'admin/clipboard_change_form.html'
    clipboard_class_name = 'your-clipboard-class'
    clipboard_fields = ()

    def get_form(self, request, obj=None, **kwargs):
        form = super(ClipboardModelAdmin, self).get_form(request, obj=None, **kwargs)
        for i in self.clipboard_fields:
            if i in form.base_fields:
                if 'class' in form.base_fields[i].widget.attrs:
                    form.base_fields[i].widget.attrs['class'] += ' '+self.clipboard_class_name
                else:
                    form.base_fields[i].widget.attrs['class'] = self.clipboard_class_name
        return form

    class Media:
        js = ('admin/clipboard.js',)

Well, then it's up to the script. With the clipboard, everything is rather crutch , ugly , but you can do it. The script must be made universal: if the field has a certain class, then it is worth adding a button "to the buffer". It doesn't matter how you do it, I would hang some kind of badge with absolute positioning, but you can also fix the template .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question