Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST jQuery array to Django

Tags:

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')
like image 436
jabez Avatar asked Aug 04 '13 17:08

jabez


1 Answers

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,

like image 87
Hieu Nguyen Avatar answered Oct 20 '22 21:10

Hieu Nguyen