在python中赋值之前引用的局部变量'form'

时间:2019-12-18 06:25:42

标签: python django

此代码始终向我显示分配前引用的错误局部变量'form'

        org.robovm.libimobiledevice.LibIMobileDeviceException: IDEVICE_E_NOT_ENOUGH_DATA
        at org.robovm.libimobiledevice.IDevice.checkResult(IDevice.java:197)
        at org.robovm.libimobiledevice.IDeviceConnection.receive(IDeviceConnection.java:109)
        at org.robovm.libimobiledevice.util.AppLauncher.receiveGdbAck(AppLauncher.java:475)
        at org.robovm.libimobiledevice.util.AppLauncher.sendReceivePacket(AppLauncher.java:485)
        at org.robovm.libimobiledevice.util.AppLauncher.pipeStdOut(AppLauncher.java:763)
        at org.robovm.libimobiledevice.util.AppLauncher.launchInternal(AppLauncher.java:734)
        at org.robovm.libimobiledevice.util.AppLauncher.launch(AppLauncher.java:1052)
        at org.robovm.compiler.target.ios.AppLauncherProcess$1.run(AppLauncherProcess.java:67)

4 个答案:

答案 0 :(得分:0)

仅当条件request.method == 'POST'满足时,才定义变量 form ,否则在功能范围内将没有 from 变量。该代码应如下所示,以解决您的问题:

if request.method=='POST':
   form = ListForm(request.POST)
else:
   form = ListForm(None)

答案 1 :(得分:0)

def home(request):
    all_items = list.object.all()
    if request.method=='POST':
        form = ListForm(request.POST or None) 
        if form.is_valid(): 
            form.save() 
            messages.success(request ,('Item Has Been Added To List !')) 
            return redirect('home.html') 
    else :
        form = ListForm()
    return render(request, 'home.html', {'all_items': all_items, 'form': form})

在获取请求的情况下,表单将再次抛出给用户

答案 2 :(得分:0)

您可以这样做,因为该语句将在and

的左侧断路
if 'form' in locals() and form.is_valid(): 
    ... do something

答案 3 :(得分:0)

def home(request):
    if request.method == 'POST':
      form = ListForm(request.POST or None)
      form = ListForm(request.POST)  
        if form.is_valid():
            form.save()
            all_items = list.objects.all
            messages.success(request, ('Item has been added to do list!'))
            return render(request, "home.html", {'all_itmes':all_items})
        else:
            print(form.errors)
            return HttpResponse(form.errors)
    else:
        all_items = list.objects.all
        return render(request, "home.html", {'all_itmes':all_items})