以下是导致错误的行:
return render(request,'boardeditor.html',{'picture':picture,'board':BoardNameForm(request.user),'boardpicture':BoardPictureForm(request.user),})
原因是 return 语句不在 if 条件下,因此它picture
在所有情况下都尝试返回变量。所以根据你的代码:
if forms.is_valid():
board = forms.cleaned_data['board']
if board == None:
picture = ""
if board:
boards = forms.cleaned_data['board']
picture = Picture.objects.filter(board=boards)
return render(request,'boardeditor.html',{'picture':picture,'board':BoardNameForm(request.user),'boardpicture':BoardPictureForm(request.user),})
如果if forms.is_valid()
条件失败,您仍在尝试返回picture
未定义的变量。您需要确保在访问它之前定义了变量。
有很多方法可以做到这一点。例如:
示例 1:
if forms.is_valid():
board = forms.cleaned_data['board']
if board:
boards = forms.cleaned_data['board']
picture = Picture.objects.filter(board=boards)
else:
picture = '' # or None or False or Whatever
return render(request,'boardeditor.html',{'picture':picture,'board':BoardNameForm(request.user),'boardpicture':BoardPictureForm(request.user),})
示例 2:
picture = '' # or None or False or Whatever
if forms.is_valid():
board = forms.cleaned_data['board']
if board:
boards = forms.cleaned_data['board']
picture = Picture.objects.filter(board=boards)
return render(request,'boardeditor.html',{'picture':picture,'board':BoardNameForm(request.user),'boardpicture':BoardPictureForm(request.user),})
示例 3:
if forms.is_valid():
board = forms.cleaned_data['board']
if board:
boards = forms.cleaned_data['board']
picture = Picture.objects.filter(board=boards)
return render(request,'boardeditor.html',{'picture':picture,'board':BoardNameForm(request.user),'boardpicture':BoardPictureForm(request.user),})
else:
return render(request,'boardeditor.html',{'picture':'','board':BoardNameForm(request.user),'boardpicture':BoardPictureForm(request.user),})
或者按照 Aldarund 的建议将所有变量放入字典中,然后将字典传递给上下文。