0

我有一个表单集,允许用户为捐赠给他们的项目的用户提供多种奖励。

如果我登陆页面并且没有输入任何信息,提交我会得到一个 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))
4

2 回答 2

1

您已经将表单集称为不同的东西 -reward_formset在 POST 块中,但只是reward在非 POST 块中。如果它是一个 POST 并且无效,它将落到底部,代码期望一个reward尚未定义的变量。

在变量命名中保持一致。

于 2011-02-17T13:27:47.510 回答
0

'reward' 仅在 else 块中可见,移动变量以实现适当的范围界定,例如:

def new(request, template_name='projects/new.html'):

    form = UserSubmittedProjectForm()
    reward = RewardFormSet(instance=Project())

    if request.POST:
       form = UserSubmittedProjectForm(request.POST, request.FILES)
       ...    

    context = { 'form':form,'reward':reward, }

    return render_to_response(template_name, context,
        context_instance=RequestContext(request))
于 2011-02-17T12:16:35.840 回答