Search⌘ K
AI Features

Updating and Deleting a Comment

Explore how to enable comment updates and deletions in a Django social media app. Learn to restrict editing and deleting permissions to comment authors, post authors, or superusers, and implement validation and permission logic for secure operations.

Updating a comment is an action that can only be done by the author of the comment. And the user should only be able to update the body field of the comment and can’t modify the author value. Let's go over the steps to add the update feature.

In core/comment/viewsets, make sure that put is in the list of http_method_names of CommentViewSet:

Python 3.8
class CommentViewSet(AbstractViewSet):
http_method_names = ('post', 'get', 'put', 'delete')

Validating post

After that, let’s write a validate method for the post field. We want to make sure that this value is not editable on PUT requests.

Inside the core/comment/serializers.py file, add a new method called validate_post to CommentSerializer:

Python 3.8
...
def validate_post(self, value):
if self.instance:
return self.instance.post
return value
...
...