没有与给定查询匹配的注释

2024-04-29 10:54:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在与Django建立一个简单的社交网络。 登录后,每个用户都可以在其个人资料上发表文章、创建组并发表文章、添加评论和删除自己的评论

添加注释可以很好地工作,但是每当我单击delete comment按钮时,我在第 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/url.py 这是我的./posts/url.py

# POST URL

from django.urls import path
from django.conf.urls import include
from . import views

app_name = 'posts'

urlpatterns = [
    # Show a list of posts as home page
    path('', views.PostList.as_view(), name="all"),
    
    # Create post view
    path('new/', views.CreatePost.as_view(), name="create"),

    # Update/Edit a post
    path('<int:pk>/edit/', views.PostUpdateView.as_view(), name="edit"),

    # Show all user posts
    path('by/<str:username>/',views.UserPosts.as_view(),name="for_user"),

    # Show a detail view of a post
    path('by/<str:username>/<int:pk>/',views.PostDetail.as_view(),name="single"),

    # Delete a post
    path('delete/<int:pk>/',views.DeletePost.as_view(),name="delete"),

    # 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/<int:id>', 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']