Reputation: 71
I'm trying to add a delete button for a single comment of current user inside a post. I tried the function below in my views.py , but it comes back as error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/comments/15/delete/ Raised by: feed.views.comment_delete
Any ideas what I'm doing wrong ?
views.py
@login_required
def comment_delete(request, pk):
comment = get_object_or_404(Comments, pk=pk)
if request.user.id == comment.username_id:
Comments.objects.get(pk=pk).delete()
messages.error(request, f'Comment Deleted')
return redirect('post-detail', pk=pk)
models.py
class Post(models.Model):
description = models.TextField(max_length=255)
pic = models.ImageField(upload_to='path/to/img', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comments(models.Model):
post = models.ForeignKey(Post, related_name='details', on_delete=models.CASCADE)
username = models.ForeignKey(User, related_name='details', on_delete=models.CASCADE)
comment = models.CharField(max_length=255)
comment_date = models.DateTimeField(default=timezone.now)
post_detail.html
<h4 class="comment_text">Comments</h4>
<div class="row">
<div class="col-xl-9 col-md-10 m-auto order-xl-2 mb-0 mb-xl-0">
{% if post.details.all %}
<div class="card card-signin my-0">
{% for detail in post.details.all %}
<div class="card-body">
<a href="{{ detail.username.profile.get_absolute_url }}">
<img src="{{ detail.username.profile.image.url }}" class="rounded-circle" width="30" height="30" alt="">
</a>
<a class="text-dark" href="{{ detail.username.profile.get_absolute_url }}"><b>{{ detail.username }}</b></a>
<a class="comment_delete" href="{% url "comment-delete" user.id %}">delete</a>
<br><small>{{ detail.comment_date }}</small><br><br>
<p class="card-text text-dark">{{ detail.comment }}</p>
</div>
<hr class="my-1">
{% endfor %}
</div>
{% else %}
<p>No comments to show!</p>
{% endif %}
</div>
Upvotes: 0
Views: 272
Reputation: 21812
In your template you write {% url "comment-delete" user.id %}
when in fact the argument that the view expects is the comments id/pk. Change it to {% url "comment-delete" detail.pk %}
Upvotes: 1