Thursday 5 September 2019

Adding Javascript to Custom widgets

This question is related to

Django: Best Way to Add Javascript to Custom Widgets

But is not the same.

The original question asks how to add supporting javascript to a custom django widget, and the answer is to use forms.Media, but that solution does not work for me. My example is this:

The widget, when rendered in a form, creates a line which looks like (toy example) this:

<div id="some-generated-id">Text here</div>

Now, what I also want to add to the output is another line looking like this:

<script>
$('#some-generated-id').datetimepicker(some-generated-options)
</script>

The initial idea is that when the widget is rendered, both the div and script get rendered, but that does not work. The problem is that the structure of the html document looks like:

-body
    - my widget
    - my widget's javascript
-script
    -calls to static files (jQuery, datetimepicker,...)

At the time the widget's javascript code is loaded in the browser, jQuery and datetimepicker js files have not yet been loaded (they load at the end of the document).

I cannot do this using Media, since the options and id I generate are vital to the function. What is the best way to solve this?



from Adding Javascript to Custom widgets

No comments:

Post a Comment