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



如何在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)

相关内容

  • 没有找到相关文章

最新更新