I have seen several posts that describe deleting items in Django with views and check boxes. I have accomplished deleting single items with AJAX. My current problem is that I cannot figure out how to delete multiple items with check boxes and AJAX in my Django application.
I originally used Django's GCBV, DeleteView
, and this worked for single-object deletions. But as @Craig Blaszczyk points out, the DeleteView
is for just that: deleting a single object. So I need to write a new view to delete multiple objects with an accompanying form and AJAX call that sends the ids
array.
I have this working but it feels clunky and doesn't work very well. My AJAX script is here:
$.ajax({
type: 'POST',
url: '/dashboard/images/delete/',
data: {'ids': ids},
success: function() {
console.log(date_time + ": AJAX call succeeded.");
},
error: function() {
console.log(date_time + ": AJAX call failed!");
console.log(date_time + ": Image ID: " + ids + ".");
}
});
In this script (above the section shown here) I build an array of ids and send as data.
So in my CBV, I'm collecting the selected ids and deleting them:
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
GalleryImage.objects.filter(pk__in=request.POST.getlist('ids[]')).delete()
return render(request, self.template_name, {'form': form})
Here is the form I'm using:
class DeleteImagesForm(forms.Form):
ids = forms.ModelMultipleChoiceField(
queryset=GalleryImage.objects.all(),
widget=forms.CheckboxSelectMultiple(),
)
What is a better way to be doing this? I feel like I hacked my way to this solution without very good practices in place.
Also, even thugh it seems to be working, I feel like I should be deleting these images after calling if form.is_valid()
.
Any final words before the bounty ends?