django:赋值前引用的UnboundLocalError局部变量

时间:2017-11-10 09:19:13

标签: python django django-forms django-views

我正在尝试使用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})

1 个答案:

答案 0 :(得分:0)

考虑代码的一部分。

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