[Answered ]-The extra function written for the DeleteView class does not work

1👍

Class based views do not work magically. They have some methods already written which are called to perform actions. Hence you writing a method delete_header_image does not mean it will be called automatically. Instead you should override some suitable method of the class which will be called internally. For DeleteView the method that performs the deletion is delete and hence you should override that. Also the condition if header_image is not None will not work since even if there is no file it will not be represented by None instead you should simply write if header_image for checking. Furthermore instead of deleting manually simply call ieldFile.delete [Django Docs]:

class NewsDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = News
    template_name = 'news/news_delete.html'
    success_url = reverse_lazy('news_list')

    def delete(self, request, *args, **kwargs):
        object = self.get_object()
        if object.header_image:
            object.header_image.delete(save=False)
        return super().delete(request, *args, **kwargs)

    def test_func(self):
        obj = self.get_object()
        if self.request.user.has_perm('news.all') or self.request.user.has_perm('news.delete_news') or obj.author == self.request.user:
            return True

Leave a comment