如何在Django UpdateView中只允许文章作者访问文章更新页面?

How to allow only the author of the article in the Django UpdateView to access the article update page?

如何在Django UpdateView中只允许文章作者访问文章更新页面?

#views.py
class ArticleUpdate(LoginRequiredMixin, UpdateView):
    model = Article
    template_name = 'articles/update_view.html'
    context_object_name = 'article_update'
    form_class = ArticleForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['securities_types_list'] = StocksETFsBonds.objects.all()
        context['tags_list'] = Tag.objects.annotate(articles_quantiy=Count('taggit_taggeditem_items')).order_by(
            '-articles_quantiy')[:10]
        return context

执行 get_object 并检查请求用户是否是文章的作者(您没有提供模型的详细信息,因此我假设您的 Article 模型具有 author 字段):

class ArticleUpdate(LoginRequiredMixin, UpdateView):
    model = Article
    template_name = 'articles/update_view.html'
    context_object_name = 'article_update'
    form_class = ArticleForm

    def get_object(self, *args, **kwargs):
        obj = super().get_object(*args, **kwargs)
        if obj.author != self.request.user:
            raise PermissionDenied()
        return obj
        
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['securities_types_list'] = StocksETFsBonds.objects.all()
        context['tags_list'] = Tag.objects.annotate(articles_quantiy=Count('taggit_taggeditem_items')).order_by(
            '-articles_quantiy')[:10]
        return context

您还可以实施 ArticleUpdate.get_queryset(如果请求用户不是文章的作者,他们会收到 404 错误):

def get_queryset(self, *args, **kwargs):
    return Article.objects.filter(author=self.request.user)