Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

python - local variable 'comment_form' referenced before assignment

I am building a BlogApp and I built a feature that if user disable comments ( through Boolean Field ) then the comments will be disabled. BUT i am stuck on an Error. When i open browser then it is showing me :-

local variable 'comment_form' referenced before assignment

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 )

I don't know . What am i missing in this.

question from:https://stackoverflow.com/questions/65862166/local-variable-comment-form-referenced-before-assignment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Comment form is inside your if statement, if post.allow is falseyour form is not callable.

Change for the following :

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 )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...