Passing an array via Ajax to Django view

0

I want to pass an array via Ajax to my Django view, but an error always occurs

  

stream_or_string = stream_or_string.read ()

     

AttributeError: 'NoneType' object has no attribute 'read'

$.ajax({
         url: 'ajax/',
         type: 'POST', 
         dataType: "json",
         data: {disciplina: array_list}, 
         success: function(data) {
              //alert("Cadastro realizado com sucesso!");
         },
         failure: function(data) { 
              //alert("Ocorreu um erro, realize a operação novamente");
         }
    }).done(function(data){
        //alert(data);
    });

view.py

for lista in serializers.deserialize("json", request.POST.get('disciplina')):
    idDisciplina = [lista]

If I do something like this

num=request.POST.get('disciplina')

It still receives if I pass only a single value and not an array

Deserialize I used based on what I found, but I did not quite understand its functionality well, can anyone help?

    
asked by anonymous 12.08.2016 / 16:28

1 answer

1

First you must inform the csrf token in order to safely submit 'POST' . Second, when you send an array, django gets the variable with brackets at the end of it, in which case it would be: request.POST.get('disciplina[]') .

See how it is received (in this example I made an array ['a', 'b'] as an example:

>>> print(request.POST)
<QueryDict: {'disciplina[]': ['a', 'b'], ...>

Note that without brackets the variable does not exist:

>>> print(request.POST.get('disciplina'))
raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'disciplina'"

With brackets:

>>> print(request.POST.get('disciplina[]'))
b

As you can see, in this way only the last item in the array is captured. To get all items you should use getlist :

>>> meu_array = request.POST.getlist('disciplina[]')
>>> print(meu_array)
['a', 'b']

To send with csrf, you can add csrfmiddlewaretoken to the dictionary:

<script>

    var array_list = ['a', 'b'];

    $.ajax({
         url: '{% url "core:teste" %}',
         method: 'POST',
         dataType: 'json',
         data: {disciplina: array_list, csrfmiddlewaretoken: '{{ csrf_token }}'},
         success: function(data) {
              alert("Cadastro realizado com sucesso!");
         },
         failure: function(data) {
              alert("Ocorreu um erro, realize a operação novamente");
         }
    }).done(function(data){
        //alert(data);
    });

</script>
    
16.08.2016 / 19:24