【问题标题】:local variable 'comment_form' referenced before assignment赋值前引用的局部变量“comment_form”
【发布时间】:2021-04-27 22:10:54
【问题描述】:

我正在构建一个 BlogApp 并且我构建了一个功能,如果用户禁用 cmets(通过布尔字段),那么 cmets 将被禁用。但我被困在一个错误上。当我打开浏览器时,它会显示给我:-

赋值前引用的局部变量“comment_form”

views.py

    def detail_view(request,id):
        data = get_object_or_404(Post,id=id)
        comments = data.comments.order_by('-created_at')
        new_comment = None

        if Post.allow_comments == True:
            if request.method == 'POST':
                comment_form = CommentForm(data=request.POST)
                if comment_form.is_valid():

            else:
                comment_form = CommentForm()

        else:
            print("Comments are Disabled")

        context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form}
        return render(request, detail.html', context )

我不知道。我错过了什么。

【问题讨论】:

  • Post.allow_commentsFalse 时,comment_form 永远不会被定义。
  • request.POST 在你的 if 语句中,放在外面

标签: python html django django-models django-views


【解决方案1】:

Comment form 在您的 if statement 中,如果 post.allow 是 false您的表单不可调用。

更改以下内容:

def detail_view(request,id):
    data = get_object_or_404(Post,id=id)
    comments = data.comments.order_by('-created_at')
    new_comment = None
    comment_form = CommentForm(data=request.POST)

    if Post.allow_comments == True:
        if request.method == 'POST':
            if comment_form.is_valid():

                comment_form.instance.post_by = data
                comment_form.instance.commented_by = request.user
                comment_form.instance.active = True
                new_comment = comment_form.save()
                return redirect('mains:detail_view',id=id)

        else:
            comment_form = CommentForm()

    else:
        print("Comments are Disabled")

    context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form}
    return render(request, detail.html', context )

【讨论】:

    猜你喜欢
    • 2022-07-10
    • 1970-01-01
    • 2013-08-02
    • 2011-11-06
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多