django unboundlocalerror formset

时间:2011-02-17 11:31:45

标签: django django-views django-errors

我有一个formset,允许用户给用户多次奖励以捐赠给他们的项目。

如果我登陆页面并且没有输入任何信息,请提交我得到一个看起来很奇怪的UnboundLocalError,因为我正在检查表单是否有效以及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))

2 个答案:

答案 0 :(得分:1)

您在POST块中调用了formset不同的东西 - reward_formset,但在非POST块中只调用了reward。如果它是POST并且无效,它将落到底部,代码期望变量reward尚未定义。

在变量命名中保持一致。

答案 1 :(得分:0)

'奖励'仅在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))