dmptrluke / django-markdownfield

A simple custom field for Django that can safely render Markdown and store it in the database.
MIT License
43 stars 13 forks source link

Admin widgets are broken when used inside inlines #13

Open anatolyivanov opened 2 years ago

anatolyivanov commented 2 years ago

Admin widgets use auto-generated JS like this (see widgets.html for source):

{{ options | json_script:options_id }}
<script nonce="{{ csp_nonce }}" type="text/javascript">
    const {{ widget.name }}_options = JSON.parse(document.getElementById('{{ options_id }}').textContent);
    const {{ widget.name }}_editor = new EasyMDE(Object.assign({
        element: document.getElementById('{{ widget.attrs.id }}'),
        hideIcons: ["side-by-side", "preview"],
        spellChecker: false,
        parsingConfig: {
            allowAtxHeaderWithoutSpace: true,
        }
    }, {{ widget.name }}_options));
</script>

It's fine for usual ModelAdmin instances, but inline admins would produce invalid code like this:

<script id="options_MZdmTr6jNmZtxZhU5tjWzw" type="application/json">{}</script>
<script nonce="" type="text/javascript">
    const tasks-0-description_options = JSON.parse(document.getElementById('options_MZdmTr6jNmZtxZhU5tjWzw').textContent);
    const tasks-0-description_editor = new EasyMDE(Object.assign({
        element: document.getElementById('id_tasks-0-description'),
        hideIcons: ["side-by-side", "preview"],
        spellChecker: false,
        parsingConfig: {
            allowAtxHeaderWithoutSpace: true,
        }
    }, tasks-0-description_options));
</script>

Obvious problem is that dash is illegal in variable names.

An obvious solution is to define the variable prefix in widget context based on self.uuid (see widgets.py) and use it instead of widget.name. As a workaround, monkey-patching markdownfield/widget.html via copying the source to any internal app and replacing {{ widget.name }}_options with {{ options_id }}_options works, although generated names like options_MZdmTr6jNmZtxZhU5tjWzw_options aren't that pretty.

P.S. I'll try to provide a MR if I have time ;)