0

我在 Django 中有一个这样的注册视图:

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

当我尝试运行视图时,我得到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

怎么了?

4

2 回答 2

0

对于GET您未定义的请求form

我建议添加

form = UserCreationForm()

行前

if request.method == 'POST':
于 2013-03-25T05:57:01.017 回答
0

如果方法未发布,则表单将进入最后一个else

你应该在request.POSTlike之外定义你的表单

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
于 2013-03-25T05:57:04.370 回答