Solutions Log

So I only have to figure things out once.

Using the jQuery Autocomplete Plugin With Django

Here’s another look into the development of ComicBinder.

There’s already a good tutorial on how to use an autocomplete plugin with Django, but I wanted to use this much snazzier plugin.

The Process

Load both jquery.autocomplete.min.js and jquery.autocomplete.css in your page.

In your form object, create a CharField to hold your autocomplete. Something like:

1
title = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'The name of a comic'}))

Create a hidden field to hold the primary key of the item you’re selecting (so you don’t have to depend on searching against a ‘name’ field or something else equally brittle):

1
title_pk = forms.IntegerField(widget=forms.HiddenInput())

Create a view to populate the autocomplete list:

1
2
3
4
5
6
7
8
9
10
11
def title_lookup(request):
    results = []
    if request.method == "GET":
        if request.GET.has_key(u'q'):
            value = request.GET[u'q']
            # Ignore queries shorter than length 3
            if len(value) > 2:
                model_results = Title.objects.filter(name__icontains=value)
                results = [ (x.__unicode__(), x.id) for x in model_results ]
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/json')

This will, of course, need a URLconf:

1
url(r'^title_lookup/$', view=title_lookup, name='title_lookup'),

And to finish it off, a bit of JavaScript in your template to call the plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
    $(function() {
        $('#id_title').autocomplete('{ % url title_lookup % }', {
            dataType: 'json',
            width: 500,
            parse: function(data) {
                return $.map(data, function(row) {
                    return { data:row, value:row[1], result:row[0] };
                });
            }
            }).result(
                function(e, data, value) {
                    $("#id_title_pk").val(value);
                }
            );
        }
    );
</script>

Sources

Comments