分配之前引用的局部变量 [英] Local Variable referenced before assignment
本文介绍了分配之前引用的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
本地
看着我的代码,我看不出有什么问题。
def add_client(request):
user = request.user
if request.method ==' POST':
form = AddClientForm(request.POST)
如果form.is_valid():
client = form.save(commit = False)
client.save()
return HttpResponseRedirect('/')
else:
form = AddClientForm()
返回render_to_response('clients / addClient.html',{'form' ,'user':user,},context_instance = RequestContext(request))
发生错误?
谢谢
解决方案
- 如果块没有输入,
- 未定义
表单
变量 - 然后尝试参考
表单
$ <$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b至于如何解决这个问题,那真的是你决定的。如果请求方法不是
POST
,那么修复程序取决于您希望代码执行的操作。I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error:
local variable 'form' referenced before assignment
Looking at my code, I can't see whats wrong.
def add_client(request): user = request.user if request.method =='POST': form = AddClientForm(request.POST) if form.is_valid(): client = form.save(commit=False) client.save() return HttpResponseRedirect('/') else: form = AddClientForm() return render_to_response('clients/addClient.html', { 'form': form, 'user': user, }, context_instance=RequestContext(request))
Anyone tell me where I went wrong?
Thanks
解决方案This is what is happening:
- The
if
block is not being entered. - The
form
variable is not defined. - You then attempt to refer to the
form
variable in thereturn
statement.
As to how to fix it, that's really for you to decide. What the fix is depends on what you want your code to do in case the request method is not
POST
.这篇关于分配之前引用的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- The
查看全文