3

I'm using DataTables. I want to let the user select multiple rows and delete them. So far I have it working so it deletes the first row in the selection using the code below.

Ajax Code:

    /* Add a click handler for the delete row */
    $('#delete').click( function() {
        /* fnGetSelected returns an array of integers - each int is a db unique id */
        var anSelected = fnGetSelected( oTable );
        delete_url = '/delete/' + anSelected[0];               
        $.ajax({                  
              url: delete_url,
              type: 'GET',
          });
        oTable.fnDeleteRow( anSelected[0] ); 
        fnReloadAjax();
    } );

Django Code:

@login_required
def delete(request, row_id):                          
     item = get_object_or_404(Items, pk=row_id, user=request.user)
     item.delete()

How could I update this to pass all the row ids to the Django back end? I guess I need to POST the anSelected array, but am not sure how to do this. What Django code would I need to process this integer array?

2 Answers 2

6

You could try sometings like this:

$(function(){
    $.post("{% url delete %}", {"ids[]": anSelected}, function(res){
    if(res.ok){
        // remove rows from your table, maybe :)
        // oTable.fnDeleteRow(anSelected);
      }else{
        alert(res.errors); 
      } 
    });
})

On the server:

@ajax_request
def test(request):
    ids = request.POST.getlist("ids[]")
    try:
        Items.objects.filter(id__in=ids).delete()
    except:
        return {"ok": False, "errors": "your error"}
    return {"ok": True}

the @ajax_request decorators is from https://bitbucket.org/offline/django-annoying/wiki/Home and let you return json response.

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

1 Comment

POST.getlist was the key here. Helpful for getting data in DJANGO from arrays resulting from forms
2

You'd need to use simplejson.loads, for example if you'd pass the anSelected array as arr you'd use something like this

from django.utils import simplejson

array = simplejson.loads(request.POST['arr'])
try:
    ModelName.objects.filter(pk__in=array).delete()
except:
    return HttpResponse(simplejson.dumps({'ok': False}))
return HttpResponse(simplejson.dumps({'ok': True}))

and in your javascript this something along these lines:

$.post(
    '/delete/',
    {arr: anSelected},
    function(data){
        if(data.ok){
            //Everything went smoothly
        }else{
            //Something failed, you can send extra info from django like the name of the exception thrown if you'd want and display it
        }
    }
);

2 Comments

Thanks. I'm getting "invalid property id" error on the {arr: anSelected} line.
Revised my code, just a syntax error because of the extra curly braces :)

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.