django unboundlocalerror 表单集
我有一个表单集,允许用户向为其项目捐赠的用户提供多种奖励。
如果我登陆页面并且未输入任何信息,请提交,我会收到一个 UnboundLocalError ,这看起来很奇怪,因为我正在检查表单以及表单集是否有效。
Exception Type: UnboundLocalError at /projects/new/
Exception Value: local variable 'reward' referenced before assignment
视图.py
def new(request, template_name='projects/new.html'):
if request.POST:
form = UserSubmittedProjectForm(request.POST, request.FILES)
if form.is_valid():
project = form.save(commit=False)
reward_formset = RewardFormSet(request.POST, instance=project)
if reward_formset.is_valid():
slug = request.POST.get("project_name")
project.slug = slugify(slug)
project.status = 'PR'
project.owner = request.user
project.money_raised = 0
project.date_published = datetime.now()
project.save()
form.save_m2m()
reward_formset.save()
signals.post_save.connect(notify_admins, sender=Project)
return HttpResponseRedirect('/projects/')
else:
form = UserSubmittedProjectForm()
reward = RewardFormSet(instance=Project())
context = { 'form':form,'reward':reward, }
return render_to_response(template_name, context,
context_instance=RequestContext(request))
I have a formset that allows user to give multiple rewards to a user for donating to their project.
If I land on the page and enter no info, submit I get a UnboundLocalError which seems strange since I am checking whether the form is valid and also the formset.
Exception Type: UnboundLocalError at /projects/new/
Exception Value: local variable 'reward' referenced before assignment
Views.py
def new(request, template_name='projects/new.html'):
if request.POST:
form = UserSubmittedProjectForm(request.POST, request.FILES)
if form.is_valid():
project = form.save(commit=False)
reward_formset = RewardFormSet(request.POST, instance=project)
if reward_formset.is_valid():
slug = request.POST.get("project_name")
project.slug = slugify(slug)
project.status = 'PR'
project.owner = request.user
project.money_raised = 0
project.date_published = datetime.now()
project.save()
form.save_m2m()
reward_formset.save()
signals.post_save.connect(notify_admins, sender=Project)
return HttpResponseRedirect('/projects/')
else:
form = UserSubmittedProjectForm()
reward = RewardFormSet(instance=Project())
context = { 'form':form,'reward':reward, }
return render_to_response(template_name, context,
context_instance=RequestContext(request))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已将表单集称为不同的东西 - POST 块中的
reward_formset
,但在非 POST 块中仅称为reward
。如果它是 POST 并且无效,它将落到底部,其中代码需要一个尚未定义的变量reward
。变量命名保持一致。
You've called the formset different things -
reward_formset
in the POST block, but justreward
in the non-POST block. If it's a POST and not valid, it will fall through to the bottom, where the code is expecting a variablereward
which has not been defined.Be consistent in your variable naming.
“奖励”仅在 else 块中可见,移动变量以实现正确的范围,例如:
'reward' is only visible within the else block, move your variables to achieve proper scoping, such as: