'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.



Solution 1:[1]

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,
            ),
        )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Telomeraz