Skip to content

Instantly share code, notes, and snippets.

@rctay
Created July 8, 2010 17:09
Show Gist options
  • Save rctay/468316 to your computer and use it in GitHub Desktop.
Save rctay/468316 to your computer and use it in GitHub Desktop.
[django] javascript widget factory
"""
Inserts JavaScript, rendered with the context built from a widget's attributes,
after a widget's rendered HTML.
"""
from django.forms.widgets import Widget
from django.template import Template
from django.template.context import Context
from django.utils.safestring import mark_safe
def javascript_widget_factory(script, base_cls=Widget):
class _JavaScriptWidget(base_cls):
_script_template = Template(script)
def render(self, name, value, attrs=None, choices=()):
str = super(_JavaScriptWidget, self).render(name, value, attrs, choices)
str_js = self._script_template.render(Context(attrs))
return mark_safe(str + '<script type="text/javascript">' + str_js + '</script>')
return _JavaScriptWidget
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment