简体   繁体   中英

Django Ajax Call and response with Render

I am new to Python and Django and I would like to do a task where the user have 2 drop downs. Item drop down and Machine drop down. The Machine drop down is filled depending on the selection of the Item drop down and at the same time a table is refreshed depending on the selection of the 2 drop downs.

I was thinking to do so, from JavaScript, onChange of Item drop down, I use an AJAX function which calls a function in view.py by providing Item selection as show in the Javascript part. On return of the Django function I use render return.

Both the JavaScript and def load_machines seems to work fine but the return render(request, 'home.html', {'machines': machines}) is calling home.html but machines is empty.

How shall I tackle such problem, any hint what to look at?

JavaScript part

<script>
    $("#exampleFormControlSelect1").change(function () {
    const url = $("#mainForm").attr("data-machines-url");
    const itemId = $(this).val();
    $.ajax({                       // initialize an AJAX request
            url: url,              
            data: {
                'itemId': itemId      // add the item id to the GET parameters
            },
            success: function (data) {   // `data` is the return of the `load_cities` view function
                
            }
        });
    });
</script>

Django Part view.py

def load_machines(request):
    item = request.GET.get('itemId')
    machines = List.objects.filter(item=item).all()
    print(machines)  // working FINE
    return render(request, 'home.html', {'machines': machines})
    

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name ='home'),
    path('ajax/load-machines/', views.load_machines, name='ajax_load_machines')
    # AJAX
]

rather than using render

return render(request, 'home.html', {'machines': machines})

you should return JsonResponse

from django.http import JsonResponse


data = {'machines': machines}

return JsonResponse(data)

doc about JsonResponse is here . You can also check out some simple tutorials like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM