I'm doing an exercise that consists of a small newspaper, I want to allow only to the Article creator to delete it, otherwise, redirect to the 'home' page. But, that's not working, I'm only being able to raise Http404.
views.py:
class ArticleDeleteView(LoginRequiredMixin, DeleteView):
model = Article
template_name = 'article_delete.html'
success_url = reverse_lazy('article_list')
def get_object(self, queryset=None):
""" Hook to ensure object is owned by request.user """
obj = super(ArticleDeleteView, self).get_object()
if not obj.author == self.request.user:
print(redirect('home'))
raise Http404
return obj
I tried to:
return redirect('home')
Instead of "raise Http404" but Django throws this error:
'HttpResponseRedirect' object has no attribute 'delete'
What's the way to solve this behavior and why it's this happening?
Thanks for your help!!
EDIT: (Following @SK. Fazlee Rabby comment, that post put me in the right path)
This works sweet! Thanks, SK. Fazlee Rabby
def dispatch(self, request, *args, **kwargs):
""" Making sure that only authors can delete Articles """
obj = self.get_object()
if obj.author != self.request.user:
messages.error(request, 'Document not deleted.')
return redirect('article_list')
messages.success(request, 'Document deleted.')
return super(ArticleDeleteView, self).dispatch(request, *args, **kwargs)