Reputation: 61
How to allow only the author of the article in the Django UpdateView to access the article update page?
#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
Upvotes: 0
Views: 177
Reputation: 4171
Implement get_object
and check if the requesting user is the author of the article (you did not provide the details of your models, so i will presume that your Article
model has a author
field):
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
You can also implement ArticleUpdate.get_queryset
(if the requesting user is not the author of the article they receive a 404 error):
def get_queryset(self, *args, **kwargs):
return Article.objects.filter(author=self.request.user)
Upvotes: 1