Search code examples
ajaxdjangosearchautocompletedjango-taggit

Django autocomplete search by tag and render Tag List


ive searched through the autocomplete packages to realize my autocomplete search. But all what ive found is autocompleting one word. I need a list of words- not just one.

It should behave like here on stack tag input. user start typing-select the tag if there is set one. Insert as many tags as he need and when hes finished the whole list of tags should render a List filtered by those tags with taggit.

But how to realize the search for many tags? Autocomplete only works for one?! or did i understand something badly wrong?


Solution

  • jQueryUI part:

    $("#id_of_your_input").keypress(function(){
        $(this).autocomplete({
            source: $(this).data('url'), ## or hard code it: source: '/api/...'
            minLength: 2,
            delay:300,
            select: function(event, ui) {
                $('#id_of_your_drop_down').val(ui.item.value);
            }
        });
    });
    

    The view which handles your $(this).data('url'):

    import json
    
    NUMBER_OF_RESULTS = 5
    
    def view_for_your_api(request):
        if not request.is_ajax():
            return HttpResponse('false')
        results = model.objects.all()[:NUMBER_OF_RESULTS]
        data = json.dumps([{'label': r.name, 'value': r.name} for r in results])
        return HttpResponse(data, 'application/json')
    

    I assumed you have r.name in your model. Replace it with your field or your neccessities