In a website having a "Comment" and "reply to a comment" system.
After each comment in the template, There's a "Add a reply" form which have a hidden input to carry the comment pk on its value attribute.
- How to prevent the end user from editing that hidden input value ?
- And If this is not possible, What would be the correct approach ?
CodePudding user response:
You can't prevent somebody from editing the value attribute, since it's client-sided.
The better approach would be to check on the server-side whether the user is permitted to comment or reply to the given post. For example, you can check if the user is a friend of the creator of the post. If it's not, you can block the request.
Example:
# models.py
class Post(models.Model):
creator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
body = models.TextField()
class User(AbstractUser):
friends = models.ManyToManyField(get_user_model())
# views.py
class CommentCreate(View):
def get(self, request, *args, **kwargs):
# retrieve the post object here
...
# check if the user is a friend of the creator
if post.creator.friends.filter(id=request.user.id).first(): # returns None if none found
# user is a friend of the creator
# do your stuff here
else:
# user is NOT a friend of the creator
raise PermissionDenied()
CodePudding user response:
- Preventing the end user from editing: You can use the html input type of hidden
<input type="hidden" value="{comment.pk}">