Search code examples
pythondjangoes6-modules

How to add script type="module" in django admin


If I want some javascript functionality in my Django admin, I usually go about it using the Media class like this:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):

    class Media:
        js = ('js/my_script.js',)

But I now have a script that is a ES6 module so I would like Django to render it like:

<script src="path/to/static/js/my_script" type="module"></script>

and using the Media class doesn't render the type="module" attribute.

Any help or tips to achieve this? Thanks


Solution

  • In your custom change_form.html template, extend the admin_change_form_document_ready block and add the event listener code

    {% extends 'admin/change_form.html' %}
    {% load static %}
    
    {% block admin_change_form_document_ready %}
    {{ block.super }}
    <script type="text/javascript" src="{% static 'app/your_file.js' %}"></script>
    {% endblock %}