Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attributes to a Django form widget's media fields?

I can render media files for a django form, through a custom widget, like this:

class TinyMCEWidget(Textarea):
    def __init__(self, attrs=None):
        if attrs is None:
            attrs = {}
        attrs.update({
            'class':'listing-template',
        })
        super().__init__(attrs)

    class Media:
        js = ('https://cdn.tiny.cloud/1/my_api_key/tinymce/5/tinymce.min.js/',)

But I need to add referrerpolicy="origin" to the script. Is there a way this can be done without a javascript hack?

How can I add attributes to a widget's media fields through the widget or form class?

This question shows how I can add an arbitrary amount of attributes to a form widget, but does not show how to add attributes to a widget's media fields, therefor my question is not a duplicate.

like image 542
Lord Elrond Avatar asked Nov 20 '25 11:11

Lord Elrond


1 Answers

You can use JS class which is in django-js-asset

from js_asset import JS


class TinyMCEWidget(Textarea):
    def __init__(self, attrs=None):
        if attrs is None:
            attrs = {}
        attrs.update(
            {
                "class": "listing-template",
            }
        )
        super().__init__(attrs)

    class Media:
        js = (
            JS(
                "https://cdn.tiny.cloud/1/my_api_key/tinymce/5/tinymce.min.js/",
                {
                    "referrerpolicy": "origin",
                },
                static=False,
            ),
        )
like image 107
Telomeraz Avatar answered Nov 22 '25 02:11

Telomeraz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!