我在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
怎么了?
答案 0 :(得分:0)
对于GET
次请求,您没有定义form
。
我建议添加
form = UserCreationForm()
行前
if request.method == 'POST':
答案 1 :(得分:0)
如果Method不是post,则表单将转到最后else
块
您应该在request.POST
之外定义表单
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