首页 > 解决方案 > 如何解决 FieldError - 无法将关键字“slug”解析为字段

问题描述

我正在制作一个帖子和评论模型。我创建了 Post and Comment 模型,看起来还不错。我可以添加帖子并评论任何特定的帖子。我正在尝试为每个发表评论的用户提供删除它的选项

这是views.py

def delete_comment(request):
    id = request.POST['comment_id']
    pk = request.POST['post_id']
    if request.method == 'POST':
        comment = get_object_or_404(Comment, id=id, pk=pk)
        try:
            comment.delete()
            messages.success(request, 'You have successfully deleted the comment')

        except:
            messages.warning(request, 'The comment could not be deleted.')

    return redirect('blog:post-detail')

这是模板:

                        <form action = "{% url 'blog:post-commentd' %}" method = "POST">
                            {% csrf_token %}
                            <input type="hidden" name="comment_id" value="{{ comment.id }}"/>
                            <input type="hidden" name="post_id" value="{{ post.id }}"/>
                            <button class="btn btn-danger btn-sm mt-1 mb-1">Delete</button>
                        </form>

这是网址

    path('blog/delete_comment/',
         delete_comment, name='post-commentd'),

这是models.py

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    content = RichTextUploadingField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
    slug = models.SlugField(blank=True, null=True, max_length=120)

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField(max_length=300, validators=[validate_comment_text])
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now=True)

标签: pythondjango

解决方案


如果我是你,我会使用链接而不是表单来删除评论,并确保只有评论的作者才能看到删除按钮。这就是我尝试这样做的方式。

{% if comment.name == user.username %}

   <button class="btn btn-danger btn-sm mt-1 mb-1" 
   onclick="location.href='{% url 'blog:delete-comment' comment.id 
   %}';">Delete</button>

{% endif %}

我的网址应该是这样的

    path('blog/delete_comment/<int:id>/',
         views.delete_comment, name='delete-comment'),

然后我的views.py

@login_required
def delete_comment(request,id):
   
        comment = get_object_or_404(Comment,id=id)
        slug    = comment.post.slug
    
        try:
            if request.user == comment.user:
               comment.delete()
               messages.success(request, 'You have successfully deleted the 
                                         comment')

        except:
            messages.warning(request, 'The comment could not be deleted.')

    return redirect('blog:post-detail', slug)

推荐阅读