Django and AJAX: delete multiple items with checkboxes

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?

+4
source share
2 answers

DeleteView, . , View, , , . ProcessFormView, .

:

class MyView(FormView):
    form_class = MyForm
    template_name = 'mytemplate.html'

    def form_valid(self, form):
        # Process your ids here
        print form.cleaned_data['ids']
        # Prints [u'1', u'2']
        return super(MyView, self).form_valid(form)

    def get_form_kwargs(self):
        form_kwargs = super(MyView, self).get_form_kwargs()
        query =  Image.objects.all().values_list('id', flat=True)
        form_kwargs['image_ids'] = [(image_id, image_id) for image_id in query]
        return form_kwargs

:

class MyForm(forms.Form):
    # This might be better as a ModelChoiecField
    ids = forms.MultipleChoiceField()#

    def __init__(self, image_ids, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['ids'].choices = image_ids
+3

id .

.

function updateTextAreanew() {
  var allVals = [];
    $('.questions_checkbox :checked').each(function() {
          allVals.push($(this).next().val());
    });
  $('.ups1').val(allVals);

}

$(function() {
  $('.questions_checkbox input').click(updateTextAreanew);

    updateTextAreanew();
});

allVals.

, id, ajax .

@csrf_exempt
def deleteitems(request):
    newdata = request.user
    profiledata = UserProfile.objects.get(user=newdata)
    swid = request.POST.getlist('newval[]') # ajax post data (which have all id of GalleryImage objects)
    for one in swid:
        obj = GalleryImage.objects.get(id=one).delete()
    response = json.dumps({'data':'deleted'})
    return HttpResponse(response, mimetype="application/json")
0

Source: https://habr.com/ru/post/1568795/


All Articles