UnboundLocalError when submitting form in Django App

Viewed 17

I am trying to submit a form but receiving an error:

UnboundLocalError at /create/ local variable 'spr' referenced before assignment

Below is the section of my views.py file that is highlighted in the error, specifically:

return HttpResponseRedirect("/%i" %spr.id)

def create(response):
if response.method == "POST":
    form = CreateNewSprint(response.POST)

    if form.is_valid():
        n = form.cleaned_data["name"]
        spr = Sprint(name=n)
        spr.save()
        response.user.sprint.add(spr)

    return HttpResponseRedirect("/%i" %spr.id)

else:
    form = CreateNewSprint()
return render(response, "main/create.html", {"form": form})

I am unsure of why this is happening, any pointers in the right direction would be greatly appreciated. If any other code/information is needed please let me know.

1 Answers

If the form.is_valid() returns False, then it will aim to evaluate return HttpResponseRedirect("/%i" %spr.id), but spr is never set in that case. You thus should in that case rerender the invalid form:

def create(response):
    if response.method == 'POST':
        form = CreateNewSprint(response.POST)

        if form.is_valid():
            n = form.cleaned_data['name']
            spr = Sprint(name=n)
            spr.save()
            response.user.sprint.add(spr)
            return HttpResponseRedirect('/%i' %spr.id)

    else:
        form = CreateNewSprint()
    return render(response, 'main/create.html', {'form': form})

Note: You can make use of redirect(…) [Django-doc] and determine the url based on the view name and the parameters. This is more safe and elegant than performing string formatting and then wrap it in a HttpResponseRedirect object [Django-doc].

Related