Django, jQuery, and autocomplete

34,096

Solution 1

If you're looking to search from within your django models then something like:

from django.utils import simplejson
    def autocompleteModel(request):
    search_qs = ModelName.objects.filter(name__startswith=request.REQUEST['search'])
    results = []
    for r in search_qs:
        results.append(r.name)
    resp = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');'
    return HttpResponse(resp, content_type='application/json')

For the jQuery autocomplete and call:

function searchOpen() {
    var search = $('#txtSearch').val()
    var data = {
        search: search
    };
    $.ajax({
        url: '/search.json',
        data: data,
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'searchResult'
    });
}


function searchResult(data) {
    $( "#txtSearch" ).autocomplete ({
        source: data
    });
}

Finally to connect it all on your input form would have something like:

<input type="text" name="search" id="txtSearch" onkeyup="searchOpen()" />

Note, this is using Jquery UI as well in addition to stock jQuery.

Solution 2

Meanwhile, a good tutorial appeared.

autocomplete does everything for you, all you have to do is the following:

js

$(function() {
  $("#search-field").autocomplete({
    source: "/ajax_calls/myFunction",
    minLength: 2,
  });
});

urls.py

url(r'^ajax_calls/myFunction/', 'my_app.views.handler_function'),

views.py

def get_drugs(request):

    if request.is_ajax():
        .....
        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

SOURCE: http://flaviusim.com/blog/AJAX-Autocomplete-Search-with-Django-and-jQuery/

Solution 3

Let's say you want to set up autocomplete on some input field (like <input type="text" id="id_input">) with the username of your users. This is the way I did it:

urls.py

First of all, add a url that will be used by the AJAX call.

url(r'^ajax/autocomplete/$', views.autocomplete, name='ajax_autocomplete')

views.py

Then set a view to retrieve the information (i.e the usernames, in this case) from the database

from django.http import JsonResponse

def autocomplete(request):
    if request.is_ajax():
        username_query = request.GET.get('username_query', '')
        usernames = (User.objects
                     .filter(username__startswith=username_query)
                     .values_list('username', flat=True))
        data = {
            'usernames': usernames,
        }
        return JsonResponse(data)

JavaScript

Finally, you need to make a JavaScript function that goes to the database and returns the usernames that match with the value of the input field every time you press (and release) a key. For this, we are going to use Ajax, JQuery and the JQuery-ui's autocomplete function

jQuery(function() {
    $("#id_input").on('keyup', function(){
        let value = $(this).val();
        $.ajax({
            url: "{% url 'ajax_autocomplete' %}",
            data: {
              'username_query': value 
            },
            dataType: 'json',
            success: function (data) {
                let usernames = data.usernames;
                $("#id_input").autocomplete({
                source: usernames,
                minLength: 3 
                });       
            }
        });        
    });
  });

And that's it! For more information, you can check out this tutorial

Solution 4

I'm a big fan of django-autocomplete: https://bitbucket.org/tyrion/django-autocomplete/wiki/Home . Its got a nice plug-and-play and is very easy to integrate with your own apps without much additional coding.

Solution 5

I know that implementing jQuery autocomplete is tricky. Here is a working example for Django > 2.0:

Step 1: Create a simple HTML with an input (Don't forget to add links to load jQuery and jquery-ui). Save the code as testsearch.html

<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> 
</head>
<div class="ui-widget">
  <label for="search"> Search </label>
  <input id="search">
</div>

Step 2: Add a JavaScript code to the html. It calls the function autocomplete from jquery-ui. This function uses a source which the URL for Ajax calls

<script type="text/javascript">
$(function() {
  $("#search").autocomplete({
    source: "{% url 'project:ajax_load_project' %}",
    minLength: 2,
  });
});
</script>

Step 3: Now we need to create two functions. A simple function to render testsearch.html and another one that receives Ajax calls and send back data.

def ajax_load_project(request):
    if request.is_ajax():
        q = request.GET.get('term', '')
        print(q)
        projects = Project.objects.filter(title__istartswith=q)[:5]
        results = []
        for project in projects:
            project_json = {}
            project_json['id'] = project.id
            project_json['value'] = project.title
            project_json['label'] = project.title
            results.append(project_json)
        data = json.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def searchProject(request):
    template = 'project/testsearch.html'
    return render(request, template)

Project is my model. You can replace it with your Model. Replace title with the field used for searching.

For my example you can create this simple Model:

class Project(models.Model):
    """
    A Model representing a the project.
    """
    title = models.CharField(max_length=200)

Step 4: Don't forget to include two URLs. One for the HTML and the one for Ajax calls

urlpatterns += [
    #test search
    path('SuggestProject/', views.ajax_load_project, name='ajax_load_project'),
    path('searchtest/', views.searchProject, name='searchProject'),]
Share:
34,096

Related videos on Youtube

harwalan
Author by

harwalan

Updated on November 03, 2020

Comments

  • harwalan
    harwalan over 3 years

    After some extensive research (Googling), I cannot find a current tutorial on how to set up autocomplete using Django and jQuery. There appears to be a variety of plugins and there appears to be no consistency or standard about which to use or when.

    I'm not a pro at either Django or jQuery, but need an autocomplete solution that is well documented and fairly simple to utilize.

    Suggestions?

  • harwalan
    harwalan about 13 years
    I looked at django-autocomplete, and it seemed a good way to go. I couldn't quite figure out how to integrate it into my form and template though. The instructions don't go that far.
  • KhoPhi
    KhoPhi almost 9 years
    simplejson is deprecated and not available in latest Djangos: docs.djangoproject.com/en/1.8/internals/deprecation
  • KhoPhi
    KhoPhi almost 9 years
    Followed tutorial. Although results are returned, they don't show in the drop downdown under the input. See my question here: stackoverflow.com/questions/31617931/…
  • ByteHamster
    ByteHamster over 8 years
    Welcome to Stack Overflow! While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. See How do I write a good answer.
  • user763410
    user763410 over 8 years
    @Nikhil Shirsath, The docs only show how to enable it for admin purposes. Is there a sample where I can see it for normal app rather than admin?
  • chiseledCoder
    chiseledCoder over 8 years
    @user763410 Here is the link of the tutorial from django-autocomplete-light: youtube.com/watch?v=fJIHiqWKUXI
  • Roel
    Roel over 7 years
    Hi, can you explain where can i put the /search.json file?
  • J0ANMM
    J0ANMM over 7 years
    It took also a while for me to make it work, and an additional question in SO. Once I figured out how to do it, I tried to make a step-by-step explanation that will hopefully be useful for others.
  • Braden Holt
    Braden Holt over 6 years
    I don't understand why people even try with django-autocomplete. I wasted about two hours trying to get it to work. This is much better and gives you much more control over your code.
  • Ganesh Jadhav
    Ganesh Jadhav over 4 years
    If your input field- 'search-field' were inside a form, how'd you do it?
  • Love Putin
    Love Putin over 4 years
    @GaneshJadhav - Have you been able to find answer to your query? I am facing a similar issue. Posted a query here. It would be nice to get to know your take on this.