为什么 Django 在用户 WAN 创建评论时会出错?

why django give an error when user wans to create a comment?

提问人:Elyas Shavikloo 提问时间:11/8/2023 最后编辑:Elyas Shavikloo 更新时间:11/8/2023 访问量:37

问:

我正在用 Django 开发一个博客网站。当未经授权的用户尝试提交评论时,我在create_comment视图中收到错误。

我的观点代码如下:

def comment_create(请求、slug、pk): pk = str(pk)

try:
    post = Post.objects.get(pk=pk)
except Post.DoesNotExist:
    # handle the case where the post does not exist
    return JsonResponse({'success': False, 'errors': {'post': ['Post with this ID not found.']}})

if request.method == 'POST':
    form = CommentForm(request.POST)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.post = post

        # check if the user has the necessary permissions to comment on the post
        if request.user.is_authenticated:
            if request.user.has_perm('blog.change_post'):
                comment.save()

                return JsonResponse({'success': True, 'comment': comment.to_dict()})
            else:
                return JsonResponse({'success': False, 'errors': {'post': ['You are not authorized to comment on this post.']}})
        else:
            return JsonResponse({'success': False, 'errors': {'user': ['Please log in.']}})

    else:
        return JsonResponse({'success': False, 'errors': form.errors})

else:
    return render(request, 'blog/post_details.html', {'post': post})

我的错误如下:

{“success”: false, “errors”: {“post”: [“找不到使用此 ID 的帖子。

我认为问题是我没有检查我的代码是否用户已登录。目前,即使用户未登录,他们也可以提交评论。

请帮我解决这个问题。

我可以添加的代码:

蟒 如果没有request.user.is_authenticated: return JsonResponse({'success': False, 'errors': {'user': ['请登录.']}})

Python Django Ajax 网友点评

评论


答:

1赞 Carl Kristensen 11/8/2023 #1

你的 Django 应用程序返回“找不到使用此 ID 发帖”错误。这通常发生在视图尝试获取具有特定 ID 的帖子时,但数据库中不存在该帖子。

下面是一些常见方案和建议,可帮助你排查和处理这种情况:

URL 或 ID 不正确:

仔细检查要传递给视图的网址参数。确保您在 URL 中使用的 pk(主键)与有效的帖子 ID 相对应。 如果您使用的是 slug,请确保 URL 中的 slug 和 pk 值格式正确。

帖子已删除或不存在:

确认您尝试访问的帖子尚未被删除。如果有,您可能希望通过通知用户或将他们重定向到相关页面来正常处理删除。

数据库完整性:

检查数据库的完整性。帖子可能未成功创建或被意外删除。你可以直接检查你的数据库,也可以使用 Django admin 浏览现有的帖子。