【问题标题】:django: UnboundLocalError local variable referenced before assignmentdjango:分配前引用的 UnboundLocalError 局部变量
【发布时间】:2017-11-10 09:19:12
【问题描述】:

我正在尝试用 django 制作一个社交网络应用程序。我制作了一个用户可以用来回答问题的表格。一切正常,但是当我提交没有任何内容的表单(空表单)时,出现错误

(Unbound Local error "local variable 'new_answer' referenced before assignment")

我是 django 的新手,对此我不太了解,所以任何帮助都会非常友好。 这是我的视图代码:

def question_detail(request, pk):
    question=get_object_or_404(Question, pk=pk)
    #list of active answers for this question
    answers = question.answers.filter(active=True)
    answer_form = AnswerForm()
    if request.method=='POST':
        #a comment was posted
        answer_form = AnswerForm(data=request.POST or None)
        if answer_form.is_valid():
            new_answer= answer_form.save(commit=False)
            new_answer.question = question
            u=request.user
            new_answer.name = u
            new_answer.save()
    else:
        answer_form = AnswerForm()
        new_answer = False
    question_tags_ids = question.tags.values_list('id', flat=True)
    similar_questions = Question.objects.filter(tags__in = question_tags_ids)\
                    .exclude(id=question.id)
    similar_questions = similar_questions.annotate(same_tags=Count('tags'))\
                    .order_by('-same_tags','-created')[:4]
    return render(request,'dashboard/post/detail.html',
              {'question':question,
               'answer_form':answer_form,
               'new_answer': new_answer,
               'similar_questions':similar_questions})

【问题讨论】:

    标签: python django django-forms django-views


    【解决方案1】:

    考虑代码部分。

    if request.method=='POST':
        #a comment was posted
        answer_form = AnswerForm(data=request.POST or None)
        if answer_form.is_valid():
            new_answer= answer_form.save(commit=False)
            new_answer.question = question
            u=request.user
            new_answer.name = u
            new_answer.save()
    

    如果用户提交了表单,如果 answer_form 无效或为空,那么你应该写一个 else 来显示错误,例如:

    if request.method=='POST':
    #a comment was posted
        answer_form = AnswerForm(data=request.POST or None)
        if answer_form.is_valid():
            new_answer= answer_form.save(commit=False)
            new_answer.question = question
            u=request.user
            new_answer.name = u
            new_answer.save()
        else:
            #code to handle invalid form submission
    

    【讨论】:

    • 感谢您的建议,现在效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    • 2020-09-26
    • 2022-01-02
    • 2019-03-22
    相关资源
    最近更新 更多