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))
'reward' is only visible within the else block, move your variables to achieve proper scoping, such as: