Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of Django Class-Based DeleteView

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 logged-in user has ownership of the object before it's deleted. Any help would be very much appreciated. Thank you in advance.

like image 927
Lockjaw Avatar asked Apr 03 '11 17:04

Lockjaw


People also ask

How do you use class based views in Django?

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

What is generic class based view in Django?

Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.

Should I use class based views in Django?

Generic class-based views are a great choice to perform all these tasks. It speeds up the development process. Django provides a set of views, mixins, and generic class-based views. Taking the advantage of it you can solve the most common tasks in web development.

Which is better class based view or function based view Django?

Class based views are excellent if you want to implement a fully functional CRUD operations in your Django application, and the same will take little time & effort to implement using function based views.


1 Answers

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.
like image 71
DrMeers Avatar answered Oct 05 '22 23:10

DrMeers