Django-异常值:赋值前引用了局部变量“ form”

时间:2018-11-29 12:31:56

标签: django forms variable-assignment

在保存搜索字词的定义中,我得到了堆栈。此定义给出错误“分配前引用的局部变量'form'”。在行上(如果form.is_valid():)。我试图重新排序,但没有成功。对于经验丰富的开发人员来说,这可能非常容易。

set.seed(1)

1 个答案:

答案 0 :(得分:0)

尝试添加它以定义表单变量:

def SearchCreateView(request):
    template_name = 'SearchCreateView_form.html'
    model = Search
    form_class = SearchCreateViewForm

    form = form_class(request.POST or None)  # ADD THIS

    if request.method == 'POST':
        if form.is_valid():
            form = SearchCreateViewForm(request.POST or None, instance=request.user)
            print(form.errors.as_text())
            search = form.save(commit=False)
            form.instance.search.user = request.user
            return render_to_response(request, 'search.html', {'form': form})
        else:
            context = {'form': form}
            return render_to_response(request, 'save.html', context)
    else:
        form = SearchCreateViewForm(request.POST or None)
            return render(request, 'SearchCreateView_form.html', {'form': form})