Passing an array via Ajax to view Django

Asked

Viewed 738 times

0

I plan to pass an array via Ajax to my Django view, but there is always an error

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]

In case I do something like that

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

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

I used deserialize based on what I found, but I did not quite understand its functionality, someone can help ?

1 answer

1

First you must inform the csrf token in order to be able to submit 'POST' safely. Second, when you send an array, Django receives the variable with brackets at the end of it, in 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'"

Square-bracketed:

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

As you can notice, this way is captured only the last item of the array. To catch all the items you should use getlist:

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

To send with csrf, you can add the 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>
  • I will be testing and I speak if it worked, but I’m still with a doubt to q the use of serializers? If you can use a basic ex would help Mut

Browser other questions tagged

You are not signed in. Login or sign up in order to post.