I start use DeleteView
of django.views.generic
.
However I am still confused about DeleteView
Document says you don't need to do anything in DeleteView
apart from UpdateView
,CreateView
So,,,,is this correct??
It doesn't delete the item.
in urls.py
path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(),
name="pre-action-delete"),
in views.py
class PreActionDeleteView(LoginRequiredMixin, DeleteView):
model = PreAction
success_url = reverse_lazy("pre-action-list")
def delete(self, request, *args, **kwargs):
success_url = self.get_success_url()
messages_text = "deleted"
messages.success(self.request, messages_text)
return HttpResponseRedirect(success_url)
CodePudding user response:
Document says you don't need to do anything in DeleteView apart from
Since you are overriding delete()
method, you have to delete the specified object manually which in you case is just to call self.object.delete()
:
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
messages_text = "deleted"
messages.success(self.request, messages_text)
return HttpResponseRedirect(success_url)
To get more information on how things get handled, see this well-structured flow diagram.
CodePudding user response:
Don't override delete()
method. It's much clearer to do such things in form_valid()
:
from django.contrib.messages.views import SuccessMessageMixin
class BookDeleteView(SuccessMessageMixin, DeleteView):
model = PreAction
success_url = reverse_lazy("pre-action-list")
def form_valid(self, form):
data_to_return = super().form_valid(form)
messages_text = "deleted"
messages.success(self.request, messages_text)
return data_to_return
Just in case, you usually need to return super()
of the method, that is normally in the View
.
Also you don't need to use return HttpResponseRedirect(success_url)
, because it's standard behaviour of DeleteView
to redirect to success_url
.