开发者

django unboundlocalerror formset

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 rende开发者_开发知识库r_to_response(template_name, context,
    context_instance=RequestContext(request))


You've called the formset different things - reward_formset in the POST block, but just reward 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 variable reward which has not been defined.

Be consistent in your variable naming.


'reward' is only visible within the else block, move your variables to achieve proper scoping, such as:

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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜