django unboundlocalerror formset

680 views Asked by At

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

There are 2 answers

0
gladysbixly On

'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
Daniel Roseman On

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.