【问题标题】:How to allow only the author of the article in the Django UpdateView to access the article update page?如何只允许Django UpdateView中文章的作者访问文章更新页面?
【发布时间】:2021-08-30 11:56:11
【问题描述】:
如何只允许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
【问题讨论】:
标签:
django
django-models
django-views
django-forms
django-templates
【解决方案1】:
实现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)