Example of Django Class-Based DeleteView

后端 未结 4 1266
长情又很酷
长情又很酷 2020-11-30 18:41

Does anyone know of or can anyone please produce a simple example of Django\'s class-based generic DeleteView? I want to subclass DeleteView and ensure that the currently lo

4条回答
  •  情深已故
    2020-11-30 19:05

    Here's a simple one:

    from django.views.generic import DeleteView
    from django.http import Http404
    
    class MyDeleteView(DeleteView):
        def get_object(self, queryset=None):
            """ Hook to ensure object is owned by request.user. """
            obj = super(MyDeleteView, self).get_object()
            if not obj.owner == self.request.user:
                raise Http404
            return obj
    

    Caveats:

    • The DeleteView won't delete on GET requests; this is your opportunity to provide a confirmation template (you can provide the name in the template_name class attribute) with a "Yes I'm sure" button which POSTs to this view
    • You may prefer an error message to a 404? In this case, override the delete method instead, check permissions after the get_object call and return a customised response.
    • Don't forget to provide a template which matches the (optionally customisable) success_url class attribute so that the user can confirm that the object has been deleted.

提交回复
热议问题