0

I have a page which displays posts of all user and user can only delete his posts. Heres the code:

class PostDelete(generic.DeleteView):
    model = Post
    template_name = 'dashboard/post_delete.html'
    success_url = reverse_lazy('dashboard:posts')

post_delete.html:

{% extends 'dashboard/sidebar.html' %}

{% block title %}Confirmation{% endblock %}

{% block mainpage %}
<div id="page-wrapper" align="center">
  <div id="page-inner">
      <h1>New post</h1>
      <form method="post">
        {% csrf_token %}
          Are you sure you want to delete?
          <br>
          <button class="btn btn-danger">Yes</button>
          <a href="{% url 'dashboard:posts' %}" class="btn btn-primary">No</a>

    </form>
  </div>
</div>
{% endblock %}

Urls.py:

path('delete/<int:pk>',views.PostDelete.as_view(),name='delete'),

How do I add user authentication code? If it were a function I would have used " if request.user.is_authenticated " But I don't know how to achieve this thing in a class. If you need an excerpt of another code then comment. Thanks!

manjy
  • 109
  • 1
  • 2
  • 12
  • I assume the user has to be the `.author`? of the `Post`? – Willem Van Onsem Jul 18 '18 at 09:03
  • Hey willem, yes that is a foreign key to my users. Thing is I can use urls to access the post_delete page, every post can be deleted and that delete view is accessed by its pk in url. For eg if my post_id is 5 then I can delete it by typing url : posts/delete/5 . Thing is this raises security issue that anyone can delete anything. Can you help what to do? – manjy Jul 18 '18 at 09:09

1 Answers1

3

Try to use UserPassesTestMixin:

from django.contrib.auth.mixins import UserPassesTestMixin

class PostDelete(UserPassesTestMixin, generic.DeleteView):
    model = Post
    template_name = 'dashboard/post_delete.html'
    success_url = reverse_lazy('dashboard:posts')
    raise_exception = True

    def test_func(self):
        self.object = self.get_object() 
        return self.object.user == self.request.user
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100