[Answered ]-UnboundLocalError when submitting form in Django App

1👍

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].

Leave a comment