I saw several posts that describe removing items in Django with views and checkboxes. I deleted individual items using AJAX. My current problem is that I cannot figure out how to remove multiple items using checkboxes and AJAX in a Django application.
I originally used Django GCBV, DeleteViewand it worked to remove individual objects. But, as @Craig Blaszczyk points out, DeleteViewit’s just for this: deleting one object. So I need to write a new view to delete several objects with an accompanying form and an AJAX call that sends the array ids.
It works for me, but it feels awkward 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 identifiers and send as data.
So, in my CBV, I collect the selected identifiers and delete 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 use:
class DeleteImagesForm(forms.Form):
ids = forms.ModelMultipleChoiceField(
queryset=GalleryImage.objects.all(),
widget=forms.CheckboxSelectMultiple(),
)
What could be better? I feel like I have cracked my way to this solution without very good practices.
Also, even if it seems like it works, it seems to me that I should delete these images after the call, if form.is_valid().
Any final words before the end of the award?