1

I wrote edit and delete view, and they work. But I soon realized anyone can edit and delete any post. I want only user who created the post to be able to delete and edit the post.

class PostUpdateView(UpdateView):
   model = Post
   form_class = PostForm
   template_name = 'main/edit.html'

   def form_valid(self, form):
      self.object = form.save(commit=False)
      self.object.save()
      return HttpResponseRedirect(self.object.get_absolute_url())

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
     return super(PostUpdateView, self).dispatch(request, *args, **kwargs)



class PostDeleteView(DeleteView):
   model = Post

   def get_success_url(self):
      return "/" 

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
      return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
Louis Barranqueiro
  • 10,058
  • 6
  • 42
  • 52
  • Possible duplicate of [Add object level permission to generic view](http://stackoverflow.com/questions/10326938/add-object-level-permission-to-generic-view) – Foon Dec 09 '15 at 12:50
  • I tried it but didn't work unfortunately, I guess I should review documentation on the generic view maybe I missed some info –  Dec 09 '15 at 13:11
  • @louis what did you edit?i don't see the difference –  Dec 09 '15 at 13:14
  • I added more accurate tags. sorry, I forgot to add comment. – Louis Barranqueiro Dec 09 '15 at 13:16
  • Oh..do you have any idea how I should approach fixing this issue? I read https://docs.djangoproject.com/en/1.9/topics/auth/default/ but it's not there. I"m new to django. I think its a simple solution but getting not fixed –  Dec 09 '15 at 13:22
  • @louis wow django community is harsh eh –  Dec 09 '15 at 13:38

1 Answers1

0

You can override the get_queryset method for your views, and filter the queryset so that only objects belonging to that user are included. For example, for your update view you would do:

class PostUpdateView(UpdateView):

    def get_queryset(self):
        queryset = super(PostUpdateView, self).get_queryset()
        return queryset.filter(user=self.request.user)
Alasdair
  • 298,606
  • 55
  • 578
  • 516