pythondjangodjango-comments

Allowing users to delete their own comments in Django


I am using the delete() function from django.contrib.comments.views.moderation module. The staff-member is allowed to delete ANY comment posts, which is completely fine. However, I would also like to give registered non-staff members the privilege to delete their OWN comment posts, and their OWN only. How can I accomplish this?


Solution

  • If you want to mark the comment as deleted, just as django.contrib.comments.views.moderation.delete() does:

    from django.contrib.auth.decorators import login_required
    from django.contrib.comments.models import Comment
    from django.shortcuts import get_object_or_404
    from django.conf import settings
    from django.contrib import comments
    
    @login_required
    def delete_own_comment(request, message_id):
        comment = get_object_or_404(comments.get_model(), pk=message_id,
                site__pk=settings.SITE_ID)
        if comment.user == request.user:
            comment.is_removed = True
            comment.save()