Johan Johan - 1 month ago 9
Ajax Question

Sending a list of checkboxes via Ajax to Django

I have a list of checkboxes in a table in my Django app. The user selects some of them and then clicks an action button. A small popup modal form then pops up, where they fill in info related to the selected items and they can also upload a file in the in the popup. I need to send the selected checkboxes' ids and the form fields in the modal to Django via ajax

I've wrapped the modal in a form tag and that all works well. I'm struggling sending the list of selected IDs to Django. When the user selects id 31 and 32, it sends it as '31,32' as a string and Django can't decode it. I'm sure it is a quick fix, but my javascript knowledge is limited.

Below is my code:

Html:

<tr>
<td ><input class="selection-box" type="checkbox" name="action" value="{{ item.id }}"></td>
<td>...</td>
</tr>
<tr>
<td ><input class="selection-box" type="checkbox" name="action" value="{{ item.id }}"></td>
<td>...</td>
</tr>


Javascript:

submitHandler: function () {
var matches = [];
$(".selection-box:checked").each(function() {
matches.push(this.value);
});
var form = document.forms.namedItem("fileinfo");// This is the popup form that contains that file upload box and other fields
var oData = new FormData(form);
if (matches.length) {
oData.append('action', matches);
}
$.ajax({
url: url,
processData: false,
contentType: false,
type: 'post',
data: oData,
success: function (data) {
if (data.success == true) {
location.reload();
}
}
});
}


Django view:

# This generates the error: ValueError: invalid literal for int() with base 10: '33,31'
selected_list = self.request.POST.getlist('action')

Answer

Since you are manually doing the 'decoding', instead of using .getlist, you can go with .get and .split:

selected_list = self.request.POST.get('action', '').split(',')

but have in mind that the returned list will contain your ids as strings, so you can use map to convert them to integers.

try:
    cleaned_list = map(int, selected_list)
except ValueError:
    #list is empty: ['']
    cleaned_list = []