Autocomplete Input Field In Django Template with Jquery-UI

by Applied Informatics

Auto-complete is one of the most important aspects of modern web interface. Auto-complete feature is used to provide auto suggestion for users while entering input. We can create auto-complete using an AJAX call to make a list and display the list using java-script. Creating auto-complete with jquery and jquery-ui is the most efficient way of creating it.

How it Works

Let’s first import jQuery and jQueryUI in our base template. The auto-complete widget uses the Jquery UI CSS to style its look and feel, so we also need to include jQuery UI.CSS.


<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript">
</script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>

Now lets add an input field in django template which needs auto-complete feature.

<input name="user_name"class="form-control "id="new-user">

This HTML code contains text input field for auto suggesting list of available users. On key-up from this input field the jQuery function is triggered.

The next step is to add our own javacsript

<script type="text/javascript">
$(function() {
$("#new-user").autocomplete({
source: "/autocomplete/newuser/",
minLength: 2,
});
});
</script>

 


jQuery Autocomplete function makes ajax call by itself. jQuery autocomplete sends the query as “term” and it expects back three fields: id, label, and value. It will use these to display label and then the value to auto-complete each user.

URL

Now add a url in urls.py which points to the view in Django Views.py

Example:url(r'^autocomplete/$',AutoCompleteView.as_view(), name='autocomplete'),

Term in Query String

When user types a string in autocomplete input field, an AJAX call is made with the ID of the input field to autocomplete function of Jquery-ui. In the source property, a url is supplied which maps to a django view. Then in view we query the model we want to with the parameter named “term”, eg. the term contains “steve”, a list is generated containing the “term”(in this case steve).

minLength

Type: Integer
Default: 1

This is the minimum number of characters a user must type before a search is performed. We can set minimum length of characters before auto-complete function is called to get the list on the basis of letters entered. This is done in minlength property in our java-script. In our case, minlength is set to 2, so atleast two characters should be entered to get the auto-suggested list.

 

//*code in view which returns json data *//
class AutoCompleteView(FormView):
def get(self,request,*args,**kwargs):
data = request.GET
username = data.get("term")
if username:
users = User.objects.filter(username__icontain s= username)
else:
users = User.objects.all()
results = []
for user in users:
user_json = {}
user_json['id'] = user.id
user_json['label'] = user.username
user_json['value'] = user.username
results.append(user_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)

In this view we query the User Model with characters contained in “term” which returns the list of matching usernames from database.

JSON data

So, when user types “applied” in autocomplete input, the AJAX call autocomplete.js?term=applied creates and returns the JSON data. Remember to import json in Django View.

If you are successful, the result is displayed in the input field as drop-down list from where one of the results can be selected. Like in our case, we can select user for the input field from the auto-suggested list of users. This  is  how we can integrate AJAX jQuery Autocomplete with Django.

To learn more about

Contact Us

Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts