Skip to content

Instantly share code, notes, and snippets.

@vorushin
Created April 5, 2010 05:48
Show Gist options
  • Save vorushin/356077 to your computer and use it in GitHub Desktop.
Save vorushin/356077 to your computer and use it in GitHub Desktop.
class AutocompleteWidget(forms.Select):
def __init__(self, attrs=None, choices=(), js_options={}):
super(AutocompleteWidget, self).__init__(attrs, choices)
self.js_options = js_options
def render(self, name, value, attrs=None, choices=()):
output = u'<input name="%(name)s" id="id_%(name)s" type="hidden">\n' % {'name': name}
value_text = ''
for ch in self.choices:
if str(ch[0]) == str(value):
value_text = ch[1]
output += u'<input name="%(name)s_text" id="id_%(name)s_text" type="text" value="%(value)s">\n' % {'name': name, 'value': value_text}
data = '[' + ', '.join(['["%s", "%s"]' % (i[1], i[0]) for i in self.choices]) + ']'
output += u'''\n<script type="text/javascript">
$(document).ready(function() {
var data = %(data)s;
$("#id_%(name)s_text").autocomplete(data, %(js_options)s);
$("#id_%(name)s_text").result(function(event, data, formatted) {
$("#id_%(name)s").val(data[1]);
});
})
</script>\n''' % {'name': name, 'data': data, 'js_options': json.dumps(self.js_options)}
return mark_safe(output)
class Media:
js = ('js/jquery-1.3.2.min.js',
'js/jquery.autocomplete.js')
css = {'all': ['css/jquery.autocomplete.css']}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment