[Django]-Return data in httpresponse for ajax call in Deleteview in django?

18👍

✅

You probably want to override delete() with something like:

from django.http import JsonResponse
from django.views.generic import DeleteView


class MyDeleteView(DeleteView)
    def delete(self, request, *args, **kwargs):
        self.get_object().delete()
        payload = {'delete': 'ok'}
        return JsonResponse(payload)

I suppose it’s a bit of a shame that you’ll need to duplicate the code that you’re overriding.

Check out CCBV if you’re unsure… http://ccbv.co.uk/DeleteView/

Disclaimer: I made CCBV.

0👍

I have problems with @meshy’s answer so I try another implementation. I hope someone will find it helpful :).
When I tried this implementation I got an ImproperlyConfigured Error, that was because I had not defined a success_ulr and the delete() method requires this parameter. So I override form_valid in this way:

class MyDeleteView(DeleteView):
     model = #'your model'
     template_name = #'your template path'
    
     def form_valid(self, form):
        self.get_object().delete()
        return HttpResponse('the response that you want')

And voila, with this change I was able to give an HttpResponse.

Leave a comment