Question

I have a registration view in django like this:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response, RequestContext, HttpResponseRedirect

def register(request):
    '''Registers the users'''

    if request.method == 'POST':
        form = UserCreationForm(request.POST)

        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect('/index/') #Returns user to user if successfully logs in

        else:
            form = UserCreationForm()    #Redirects to the UserCreationForm is the form is invalid
            return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))

    else:
        return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))

When I try to run the view I get UnBound LocalError.

#Full exception:
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/zurelsoft/workspace/fyp/summary/views.py" in register
  20.         return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))

Exception Type: UnboundLocalError at /
Exception Value: local variable 'form' referenced before assignment

What's wrong?

Was it helpful?

Solution

If Method is not post then form is going to the last else block

you should define your form outside the request.POST like

def register(request):
    '''Registers the users'''
    form = UserCreationForm()
    if request.method == 'POST':
        form = UserCreationForm(request.POST)

        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect('/index/') #Returns user to user if successfully logs in

        else:
            form = UserCreationForm()    #Redirects to the UserCreationForm is the form is invalid
            return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))

    else:
        return render_to_response('registration/register.html', {'form':form}, con

OTHER TIPS

For GET requests you are not defining form.

I would suggest to add

form = UserCreationForm()

before line

if request.method == 'POST':
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top