| Version 2 (modified by , 19 years ago) ( diff ) |
|---|
It's heavily based on AJAXWidgetComboBox, but i've modified it to make it work with YUI autocomplete widget.
Requirements
- http://developer.yahoo.com/yui/ - used for AJAX and widget implementation.
- simplejson
Installation
- Install Yahoo! UI in media/js
Example Use
I'll use the same models that in AJAXWidgetComboBox, except that we use "query=" instead of "q=" in search, so you can refer it. The urls.py looks exactly tike this last, but in view.py we have this:
...
from django.utils import simplejson
...
def json_lookup(request, queryset, field, limit=5, login_required=False):
if login_required and not request.user.is_authenticated():
return redirect_to_login(request.path)
obj_list = []
lookup = { '%s__icontains' % field: request.GET['query'],}
for obj in queryset.filter(**lookup)[:limit]:
obj_list.append({"id": obj.id, "name": getattr(obj, field)})
object = {"ResultSet": { "total": str(limit), "Result": obj_list } }
return HttpResponse(simplejson.dumps(object), mimetype='application/javascript')
Template
In template we must put the javascript. I've done it in header section with a event to fire it. So you can put the following code in your content, or in your header if you fire it with an event:
<input id="field" type="text">
<div id="container"></div>
<!-- Dependencies -->
<script type="text/javascript" src="media/js/yahoo.js"></script>
<script type="text/javascript" src="media/js/dom.js"></script>
<script type="text/javascript" src="media/js/event.js"></script>
<script type="text/javascript" src="media/js/connection.js"></script>
<script type="text/javascript" src="media/js/animation.js"></script>
<script type="text/javascript" src="media/js/json.js"></script>
<script type="text/javascript" src="media/js/autocomplete.js"></script>
<script type="text/javascript">
DataSource = new YAHOO.widget.DS_XHR("/myapp/reporter_lookup/", ["ResultSet.Result","name","id"]);
AutoComp = new YAHOO.widget.AutoComplete("field","container",DataSource);
</script>
It's all!. You can customize AutoComp and DataSource all you need with extra params.