Jquery UI Autocomplete 1.8 with Django Views

I have a model named "Show" and it has a ForeignKey to a model named "Venue." When users add a "Show" I wanted an autocomplete(d) field venue. This solution uses:

  • jquery-1.6.1.min.js
  • jquery-ui.min.js

models.py

class Venue(models.Model):
        name = models.CharField(max_length=255, blank=False, null=False, help_text="Name of the venue")

class Show(models.Model):
        date = models.DateTimeField(blank=False, null=False)
        venue = models.ForeignKey(Venue)
        headliner = models.ForeignKey(Artist, related_name="Headliner")

urls.py

(r'venue_lookup/$','projname.appname.views.venue_lookup'),

views.py

def venue_lookup(request):
   venues = Venue.objects.filter(name__istartswith=request.REQUEST['term'])
   results = []
   for venue in venues:
      venue_dict = {'id':venue.id, 'label':venue.name, 'value':venue.name}
      results.append(venue_dict)
   return HttpResponse(simplejson.dumps(results),mimetype='application/json')

Template:

<html>
<head>
<script type="text/javascript" src="/media/jquery-1.6.2.js"></script>
<script type="text/javascript" src="/media/jquery-ui.js"></script>
<script>
        $( "#id_venue" ).autocomplete({
           source: "/venue_lookup/",
           selectFirst:true,
           minLength:2
        });

</script>
</head>
<body>
<form method="post" action="/shows/new">
        <p><label for="id_venue">Venue</label>
        <input type="text" id="id_venue" name="venue" /></p>
	<input type="submit" value="done" />
</form>

</body>
</html>
Tagged as django , jquery
Written by Andrew Konkol on August 3rd, 2011

3 Comments

I don't think you finished the example. Also, I can't see the end of your mimetype (shows only "'application/" for me.

uri
August 3, 2011
You are correct uri, something went wrong when I posted the html for this example. I have added the html content... as far as seeing past "application/" hover over the code and click the "" button.

Andrew Konkol
August 3, 2011
he have to do forms.py .and mention that on views.py

Anish Menon
June 6, 2013
Log in with Twitter, Google, Facebook, LinkedIn to leave a comment.