I am trying to allow a logged in user to delete their comment under a comment section, but I keep getting the error thrown in the title, and I'm not sure why. I've read up on Managers in the docs but don't quite understand what the issue is, as all my other models work just fine. Here is the code
views.py
def delete_comment(request, comment_id):
comment_details = Comment.objects.get(id=comment_id)
# Throws error at this line
Comment.objects.remove(comment_details)
return HttpResponseRedirect('view')
models.py
class Comment(models.Model):
comment = models.CharField(max_length=64)
item = models.ForeignKey('Listing', on_delete=models.CASCADE, null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.comment}"
CodePudding user response:
Comment.objects
is an object manager of Comment
model. To erase the Comment
object you have already got, you have to delete()
it:
def delete_comment(request, comment_id):
comment_details = Comment.objects.get(id=comment_id)
comment_details.delete()
return HttpResponseRedirect('view')
Or simpler:
def delete_comment(request, comment_id):
Comment.objects.get(id=comment_id).delete()
return HttpResponseRedirect('view')