1

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.

2
  • are you getting any error? check in network, what data you're sending? Commented Dec 3, 2019 at 13:11
  • Post the error as well Commented Dec 3, 2019 at 13:11

1 Answer 1

2

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.