Reputation: 1353
I'm trying to send an array to my python
function inside views.py
but I can't. It always crash with a keyError
because is not recognising the data from js
.
Code:
Python function in views.py:
def cargar_datos_csv(request):
if request.method == 'POST':
filtros = request.POST['node']
print(filtros)
ctx = {'A':filtros}
return JsonResponse(ctx)
JS
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var frutas = ['Manzana', 'Banana'];
$.ajax({
url: '/../../data_bbdd/',
type: 'POST',
headers:{"X-CSRFToken": csrftoken},
data: {
'node': frutas,
},
dataType: "json",
cache: true,
success: function(response) {
coords = JSON.stringify(response.A);
alert(coords);
}
});
How can I send an array to my python function?
Thank you very much.
Upvotes: 1
Views: 185
Reputation: 86
Because node
is a list it will be posted as node[]
by JQuery so you can get it using request.POST['node[]']
or request.POST.getlist('node[]')
More informations on why this is the behavior of JQuery on this stackoverflow's answer :django - getlist()
Upvotes: 2