Ни один комментарий не соответствует заданному запросу

Я создаю простую социальную сеть с помощью Django. При входе в систему каждый пользователь может делать сообщения в своем профиле, создавать группу и делать сообщения, добавлять комментарии и удалять свои собственные комментарии.

Добавление комментария работает нормально, но всякий раз, когда я нажимаю кнопку удаления комментария, я получаю ошибку в строке comment = get_object_or_404(models.Comment,author=request.user, pk=post.pk), которая говорит

Page not found (404)
No Comment matches the given query.
Request Method: GET
Request URL:    http://127.0.0.1:8000/posts/comment/7/remove/
Raised by:  posts.views.comment_remove

Вот мой код для части комментариев ./posts/templates/posts/post.html

            <!-- Logged in user can view comments, add new comments, and delete their own comments -->
            {% if user.is_authenticated %}
                <!-- A button to add a comment to a post -->
                <a class="btn btn-simple" title="add-comment" href="{% url 'posts:add_comment_to_post' pk=post.pk %}">
                <span class="glyphicon glyphicon-comment"></span> Add comment</a>
                <div class="container">
            
                <!-- Displays all comments, their author and their post dates -->
                {% for comment in post.comments.all %}
                    <p>{{ comment.message|safe|linebreaks }}</p>
                    <p>Posted by: <strong>{{ comment.author }}</strong> 
                    at <time class="time">{{ comment.created_date }}</time>

                    <!-- A button to remove user's own comment -->
                    {% if comment.author == user %}
                        <a href="{% url 'posts:comment_remove' pk=post.pk %}" title="delete" class="btn btn-simple">
                        <span class="glyphicon glyphicon-remove text-danger" aria-hidden="true"> </span>
                        <span class="text-danger icon-label">Delete comment</span></a></p>
                    {% endif %}
            
                {% empty %}
                <p>No comments posted.</p>
                {% endfor %}
            {% endif %}

./posts/views.py


# Must log in to add comment to post
@login_required
def add_comment_to_post(request, pk):
    post = get_object_or_404(models.Post, pk=pk)
    if request.method == "POST":
        form = forms.CommentForm(request.POST)
        if form.is_valid():
            # Grabs the comment, not posting it yet, but connect it to a post then post it
            comment = form.save(commit=False)
            comment.author=request.user
            comment.post = post
            comment.save()
            return redirect('posts:single', username=post.user.username, pk=post.pk)
    else: # User hasn't filled out the comment form
        form = forms.CommentForm()
    return render(request, 'posts/comment_form.html', {'form': form})


# Must log in to delete comment 
@login_required
def comment_remove(request, pk):
    post = get_object_or_404(models.Post, pk=pk)
    # Error at the line below!!
    comment = get_object_or_404(models.Comment,author=request.user, pk=post.pk)
    # if comment.author == request.user:
    comment.delete()
    # We can't do pk=comment.post.pk, because we already deleted the comment
    return redirect('posts:single', username=post.user.username, pk=post.pk)

./posts/urls.py

    # Add comment to a post
    path('comment/<int:pk>/', views.add_comment_to_post, name="add_comment_to_post"),

    # Delete comment
    path('comment/<int:pk>/remove/', views.comment_remove, name="comment_remove"),
    ]

./posts/models.py

class Comment(models.Model):
    # Connect the comments to the post and user
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    # Only logged in user can comment
    author = models.ForeignKey(User, related_name='author', default="", on_delete=models.CASCADE)
    message = models.TextField()
    # Post content that is uneditable (for save function) 
    message_html = models.TextField(editable=False)
    created_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.message

    # After making a comment, returns to the detail page of the post you just commented on
    def get_absolute_url(self):
        return reverse("posts:single", kwargs={'username': self.post.user.username, 'pk':self.post.pk})

    def save(self, *args, **kwargs):
        # If user uses Markdown, misaka won't display strange Markdown brackets/notations 
        self.message_html = misaka.html(self.message)
        super().save(*args, **kwargs)

.posts/forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        # Connects message in Comment model to the form
        model = models.Comment
        fields = ['message']
Вернуться на верх