Django 2.1-DeleteView-只有所有者可以删除或重定向

时间:2018-10-05 22:26:36

标签: python django django-class-based-views

我正在做一个包含小报纸的练习,我只希望允许文章创建者删除它,否则,请重定向到“主页”页面。但是,这行不通,我只能引发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

我试图:

return redirect('home') 

而不是“ raise Http404”,但是Django抛出此错误:

'HttpResponseRedirect' object has no attribute 'delete'

解决此问题的方式是什么,为什么会发生这种情况?

感谢您的帮助!


编辑:(在@SK之后。FazleeRabby评论,该帖子使我走上了正确的道路)

这很不错!谢谢,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)

1 个答案:

答案 0 :(得分:0)

首先 如果您需要更改删除对象的行为,则应该覆盖delete方法而不是get_object,而get_object只是为了获取对象(如果引发404 django处理此错误并返回http404)

您应该这样编写代码:

class ArticleDeleteView(LoginRequiredMixin, DeleteView):
    model = Article
    template_name = 'article_delete.html'
    success_url = reverse_lazy('article_list')

    def delete(self, request, *args, **kwargs):
        """
        Call the delete() method on the fetched object and then redirect to the
        success URL.
        """
        self.object = self.get_object()
        success_url = self.get_success_url()
        if self.object.author == self.request.user:
            return redirect('confirm_deleting', ) # Also add id of Article

        return redirect('home')


class ConfirmingArticleDeleteView(LoginRequiredMixin, DeleteView):
    model = Article
    template_name = 'article_delete.html' # need change
    success_url = reverse_lazy('article_list')

    def delete(self, request, *args, **kwargs):
        """
        Call the delete() method on the fetched object and then redirect to the
        success URL.
        """
        self.object = self.get_object()
        success_url = self.get_success_url()
        if self.object.author == self.request.user:
            self.object.delete()
            return redirect('home')

        return redirect('home')