django class based delete view and validation

4.9k views Asked by At

My view:

class ModEmailDeleteView(DetailView):
    model = EmailModel
    template_name = "email_delete.html"
    success_url = reverse_lazy('moderator_profile', request.user.id)

Here I want to check if the user of particular filed is request user then only he can delete. Like

if obj.user == request.user

then only he can delete or throw 404

Also what if I have multiple primary key in the url?? and want different validations using those primary keys

2

There are 2 answers

0
ruddra On

You can do it like this:

class ModEmailDeleteView(DeleteView):
    model = EmailModel
    template_name = "email_delete.html"
    success_url = reverse_lazy('moderator_profile', request.user.id)

    def delete(self, request, *args, **kwargs):
       self.object = self.get_object()
       if self.object.user == request.user:
          self.object.delete()
          return HttpResponseRedirect(self.get_success_url())
       else:
          raise Http404 #or return HttpResponse('404_url')
0
AudioBubble On

There is mixin for django Deleview , you just override the delete function in your view,

class DeletionMixin(object):
"""
A mixin providing the ability to delete objects
"""
success_url = None

def delete(self, request, *args, **kwargs):
    """
    Calls the delete() method on the fetched object and then
    redirects to the success URL.
    """
    if self.object.user = request.user:
      self.object.delete()        
    success_url = self.get_success_url()
    self.object.delete()
    return HttpResponseRedirect(success_url)