Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Best Way to Add Javascript to Custom Widgets

Tags:

django

widget

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.

like image 931
Koobz Avatar asked Feb 09 '10 03:02

Koobz


People also ask

What is widget JavaScript?

The js file contains specific JavaScript code that implements a widget as an element of the user interface. Examples are shown of how to extend existing widgets and implement the changes by registering them as new widget classes.

What is widget tweaks in Django?

The Django widget tweaks is used to render form fields in templates. This allows you to adjust the properties of the form (such as method and CSS class) on the back-end without rewriting the template.


1 Answers

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

like image 70
buckley Avatar answered Sep 17 '22 13:09

buckley