POST jQuery array to Django

19,154

Solution 1

You can try to use tasks[] instead of tasks as parameter when sending via ajax. Example:

$('.btn-group').find('#mark_as_done').on('click', function() {
    var tasks = grab_selected();

    $.ajax({
        type: 'POST',
        url: '/edit_lists/',
        data: {'tasks[]': tasks},
    });
});

Another thing is you are simply returning return tasks in edit_lists() view, you have return a HttpResponse instance or use shortcut like render:

from django.http import HttpResponse

def edit_lists(request):
    tasks = request.POST.getlist('tasks[]')
    return HttpResponse('Success')

Hope it helps,

Solution 2

You can try to use JSON.stringify() method instead of tasks as parameter when sending via Ajax.

Here's the array data on my consol

enter image description here

Then send Array data by ajax

$.ajax({
     type: "POST",
     url: "/user/Survey-Design/",
     headers: {
         'Authorization': "Token " + localStorage.access_token
     },
     data: {
         'arr': JSON.stringify(arr)
     },
     success: function(result) {
         alert('Data Has been saved')
     }
 });

In views.py:

 def create(self,request):
     array_data = request.POST['arr']
     data = json.loads(array_data)
     print(data)
     return HttpResponse('Success')

Finally, show print(data) on terminal

enter image description here

Share:
19,154

Related videos on Youtube

jabez
Author by

jabez

Updated on June 07, 2022

Comments

  • jabez
    jabez almost 2 years

    I'm trying to POST a jQuery array of simple numbers to Django, and I really can't make it work. I need a little help on this. I'm getting an Http 500 with the following error:

    Internal Server Error: /edit_lists/
    Traceback (most recent call last):
      File "/home/jabez/.virtualenvs/hackernews/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response
        response = middleware_method(request, response)
      File "/home/jabez/.virtualenvs/hackernews/local/lib/python2.7/site-packages/django/middleware/common.py", line 106, in process_response
        if response.status_code == 404:
    AttributeError: 'list' object has no attribute 'status_code'
    

    Here's my code:

    JavaScript

        $('.btn-group').find('#mark_as_done').on('click', function() {
        var tasks = grab_selected();
    
        $.ajax({
            type: 'POST',
            url: '/edit_lists/',
            data: {'tasks': tasks},
        });
    });
    
    function grab_selected() {
        var tasks = [];
        $('input:checked').each(function() {
            tasks.push(this.id);
        });
        return tasks;
    }
    

    views.py

    def edit_lists(request):
    tasks = request.POST.getlist('tasks')
    return tasks
    

    urls.py

    url(r'^edit_lists/$', 'todo.views.edit_lists', name='edit_lists')
    
  • jabez
    jabez almost 11 years
    it worked now :). I can't believe the answer was so simple. thank you very much!
  • Pawan
    Pawan over 9 years
    How come you are sending tasks[] from ajax and able to retrieve via tasks variable. I tried in one of my example. I am getting empty list in django view. If I use request.POST.getlist('tasks[]') and if list in ajax is ['1','2'] then I am getting [u'1',u'2'] in django view.
  • Hieu Nguyen
    Hieu Nguyen over 9 years
    @Pawan hmm pretty sure I tested when I gave the answer 1.5 years ago, maybe things were different back then. I will update my answer then, cheers!
  • Pawan
    Pawan over 9 years
    Even if you send list by variable named tasks , then jQuery POST's arrays with the [] suffix because PHP and some web frameworks understand that convention, and re-build the array on the server-side for you automatically. Django doesn't work that way , but we can access the data via tasks[]
  • nidHi
    nidHi almost 8 years
    selected = request.GET.getlist[‌​‌​'selected[]'] TypeError: 'instancemethod' object has no attribute '__getitem__' I get this error...I have an array of stings like ["one","two","three"‌​‌​] and am using a GET request...
  • Hieu Nguyen
    Hieu Nguyen almost 8 years
    @nidHi it should be selected = request.GET.getlist(​‌​‌​'selected[]') (notice the brackets) since it's a method, not a dictionary
  • nidHi
    nidHi almost 8 years
    @HieuNguyen... Thank you for pointing that out... I completely missed out on the brackets...
  • Randy Tang
    Randy Tang over 7 years
    From my tests, 'request.POST.get('tasks')' actually returns a list with only one element, which is a string consisting of all ids separated by commas. Is it correct?
  • Dan Walters
    Dan Walters over 4 years
    Works perfectly with AJAZ > Django. Thanks.