16

I'm writing a custom widget that requires some supporting javascript code that I need output somehwere.

The options are:

  1. Dump it right after the html code.
  2. Append it to the form's media.
  3. Append it to a global onReady section.

My gut instinct is to avoid things like:

<!-- original widget output -->
<input id="date" />
<-- Appended javascript -->
<script type="text/javascript">
jQuery('#date').datepicker()
</script> 

Instead, I've opted for item 3) most recently in my PHP projects. Does Django have a nice way of doing 2 or 3? I'm hoping that I can utilize this methodology from the context of my widget's render function. This may preclude option 2) if my widget doesn't have a any idea of the form it's on.

Koobz
  • 6,928
  • 6
  • 41
  • 53

2 Answers2

14

Take a look at form media http://docs.djangoproject.com/en/dev/topics/forms/media/#topics-forms-media

buckley
  • 2,060
  • 1
  • 17
  • 12
  • 3
    Duh. Well that was obvious ;) The one thing about this is that it's capable of including files, but doesn't seem to have the ability to append a unique script chunk alongside it. I could change my approach and use class based selectors to attach, in this case, jQuery datepickers. – Koobz Feb 09 '10 at 05:10
  • 1
    I know this is years after the original question, but what about dynamic scripts? This only adds script files, but say I want to add a script like `$(#S_1`).datetimepicker({S_2}), and I construct the strings S_1 and S_2 programatically? – 5xum Aug 25 '15 at 19:50
4

If you're looking at adding some inline JavaScript below your Django form field you can add overwrite the render method on a form field. Below I've created a custom input field, grabbed the rendered HTML and appended a new <script>...</script> to the output.

from django import forms
from django.utils.safestring import mark_safe

class CustomInputField(forms.TextInput):

    def render(self, name, value, attrs=None, renderer=None):
        html = super().render(name, value, attrs)
        inline_code = mark_safe(
            "<script>jQuery('#date').datepicker()</script>"
        )
        return html + inline_code

This will put the right below your form field in the HTML.

Kalob Taulien
  • 1,817
  • 17
  • 22