在保存几乎相同类型的表单时,我遇到了这个错误(UnboundLocalError本地变量'context'在赋值前被引用(,其他表单运行良好,但这个表单不正常,并显示错误
def clutchDetail(request):
clutchDetail = ClutchDetail.objects.all()
context = {'title': 'Clutch Detail',
'active': 'active',
'clutchDetail': clutchDetail,
}
return render(request, 'breedingRecApp/clutch_detail.html', context)
def clutchDetail_add(请求(:
if request.method == "POST":
form = ClutchDetail_AddModelForm(request.POST or None)
if form.is_valid():
try:
form.save()
return redirect('breedingRecApp:clutch_detail')
except:
pass
else:
form = ClutchDetail_AddModelForm()
context = {'title': 'Species Detail Add',
'active': 'active',
'model': ClutchDetail,
'form': form,
}
return render(request, 'breedingRecApp/clutch_detail_add.html', context)
请帮我修复这个错误,我是Django的新手。我有另一个表单代码,它100%相同,运行良好,但这一个给了我一个错误,我被卡住了:(
谈论第二个代码块
唯一的地方
context
定义在第12行上
context = {'title': 'Species Detail Add',
这只在else:语句被触发时运行,所以当
return render(request, 'breedingRecApp/clutch_detail_add.html', context)
如果未触发else语句,则不会定义上下文干杯
出现此错误的原因是您的函数包含一个代码路径,在该代码路径中,使用context
变量,而没有首先定义变量。例如,当您发出POST请求,但form.is_valid()
检查失败时就是这种情况。在这种情况下,代码流将调用render(..)
函数,但您没有定义context
变量。
最小的修复可能是将context
变量的定义移动到else
语句之外:
def clutchDetail_add(request):
if request.method == 'POST':
form = ClutchDetail_AddModelForm(request.POST)
if form.is_valid():
form.save()
return redirect('breedingRecApp:clutch_detail')
else:
form = ClutchDetail_AddModelForm()
context= {
'title': 'Species Detail Add',
'active': 'active',
'model': ClutchDetail,
'form': form,
}
return render(request, 'breedingRecApp/clutch_detail_add.html', context)
如果方法是POST,并且form.is_valid()
返回False
,或者form.save()
引发异常,则会引发此错误,因为您从未声明上下文变量。
您可能也不需要在form.save()
调用中执行try: except:
,因为此时表单是有效的。
def clutchDetail(request):
clutchDetail = ClutchDetail.objects.all()
context = {'title': 'Clutch Detail',
'active': 'active',
'clutchDetail': clutchDetail,
}
return render(request, 'breedingRecApp/clutch_detail.html', context)
def clutchDetail_add(request):
if request.method == "POST":
form = ClutchDetail_AddModelForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('breedingRecApp:clutch_detail')
else:
form = ClutchDetail_AddModelForm()
context = {'title': 'Species Detail Add',
'active': 'active',
'model': ClutchDetail,
'form': form,
}
return render(request, 'breedingRecApp/clutch_detail_add.html', context)