1

Hy, I am developing a Django Blog application. In this application, I have a PostEdit view to edit the post, Delete post view to delete the post. These operations can only be performed by the user who has created that post. I used Delete view as a functional view and edit view as CBV. Now what is happening is that any user is able to delete or edit the others post through URL. In my delete post view since it is a functional based view, I have used if condition to prevent another user to prevent deleting someone else post. But since for post edit, I am using CBV, I am not able to find a way to prevent a user from editing someone else's post.

So how can I prevent doing another user to edit someone else post?


class PostUpdateView(LoginRequiredMixin ,UpdateView):
    model = Post
    template_name = 'blog/post_form.html'
    form_class = PostForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Update'
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.save()
        return super().form_valid(form)


@login_required
def post_delete(request, slug):
    post = get_object_or_404(Post, slug=slug)
    if (request.user == post.author):
        post.delete()
        return redirect('blog:post_list')
    else:
        return redirect('blog:post_detail', slug=slug)
Gaurav Sahu
  • 181
  • 3
  • 11

1 Answers1

1

You can filter the queryset on the logged in user, by overriding get_queryset method [Django-doc], like:

class PostUpdateView(LoginRequiredMixin ,UpdateView):
    model = Post
    template_name = 'blog/post_form.html'
    form_class = PostForm

    def get_queryset(self):
        return super().get_queryset().filter(author=self.request.user)

    # ...

In case a user aims to edit a Post of which he/she is not the author. The view will raise a 404 error.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • This works. Also, I want you to notice that it should be `self.request.user` instead `request.user`. Also, I want to ask you for general Is there any other method instead of an if condition to achieve this purpose in function based view. – Gaurav Sahu Jun 23 '19 at 17:55