martina.physics
martina.physics

Reputation: 9804

Django - how to pass more than one primary key to the view

I need to write a view to delete multiple objects in one go. I have modified the HTML template, put checkboxes to select which objects (users) to delete and a button to delete them, but of course you need a view to perform the task.

When you have one item to select at a time, you pass its primary key to the view through the url, how can I extend this to pass more than one primary key?

Upvotes: 1

Views: 1344

Answers (2)

oxymor0n
oxymor0n

Reputation: 1097

What you can do is to send the data in a JSON format, which can easily be decoded by Django

On the frontend, you'd have a JavaScript for a button like so,

function delete_object(pks) {
    var args = {type: "POST", url: "/delete/", data: {'pks': pks}};
    $.ajax(args);
    return false;
}

this function would take selected the primary keys from (which is passed in as pks) and POST it to the Django url ^delete/$. A Django view function can then handle the incoming data like so,

def delete(request):
    object_pks = request.POST['pks']
    Docs.objects.filter(pk__in=object_pks).delete()

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599778

You would absolutely not be doing this via the URL. If you have a set of checkboxes, then you have a form; since the form is doing destructive operations it will be submitted via POST: therefore your set of IDs is in request.POST.

Upvotes: 4

Related Questions