Auto Complete Django

Auto Complete Django

Bagaimana membuat form auto complete pada django ?

Buat sebuah form

<div>
    Hotel Name: <input type="text" id="ean_hotel" name="hotel_name" />
   ID_Ean : <input type="text" id="id_ean" name="id_ean" />
</div>

 

Buat scrip auto complete dengan jquery

<script type="text/javascript">
$(document).ready(function(){
    var ac_config = {
        source:'http://localhost:8002/properties/p-auto',
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
    select: function(event, ui) {
        $('#id_ean').val(ui.item.property_id);
        event.preventDefault();
        $("#ean_hotel").val(ui.item.properties_name); },
        minLength:1
    };
    $("#ean_hotel").autocomplete(ac_config);
});
</script>

 

buat function untuk mengolah data jsonĀ 

def get_auto_properties(request):
    propertyGet = request.GET.get('term')
    getProperties = Propertiesmodel.objects.filter(name__contains=propertyGet)
 
    lst = []
    for x in getProperties:
        d = {}
        d['ean_hotel_id'] = x.ean_hotel_id
        d['property_id'] = x.property_id
        d['properties_name'] = x.name
        lst.append(d)
 
    response = json.dumps(lst, default=myconverter)
    return HttpResponse(response)
 
def myconverter(o):
    if isinstance(o, datetime):
        return o.__str__()

 

good luck …!

mm

Alfin F

Technopreneur , Developer, Advisor

More Posts

Follow Me:
TwitterLinkedIn