我在Django 1.0网站开发中复制了一个用户注册页面的简单示例。我已经定义了以下形式:
class RegistrationForm(forms.Form):
username = forms.CharField(label=u'Username', max_length=30)
email = forms.EmailField(label=u'Email')
password1 = forms.CharField(
label=u'Password',
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label=u'Password (Again)',
widget=forms.PasswordInput()
)
def clean_password2(self):
if 'password1' in self.cleaned_data:
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
print "Validating username..."
username = self.cleaned_data['username']
if not re.search(r'^\w+', username):
raise forms.ValidationError('Username can only contain '
'alphanumeric characters and the underscore.')
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError('Username is already taken')
如果已经使用了用户名,则使用普通表单验证验证该字段,并且不调用我的自定义清理方法。当表单提交到register_page时,form.is_valid()返回True。
为了让Django知道调用clean_方法,是否需要完成某些工作?
def register_page(request):
if request.method == 'POST':
print "Posted to registration form"
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/')
else:
form = RegistrationForm()
return render_to_response(
'users/registration.html',
context_instance=RequestContext(request, {
'form' : form
})
答案 0 :(得分:4)
如果有其他人通过谷歌到达这里并且上述答案没有帮助:
我遇到了同样的问题,事实证明我并没有将排除设置为我的表单元组中的元组:
class MyFormClass(ModelForm):
class Meta:
exclude = ('type_detail') #wrong
而不是:
class MyFormClass(ModelForm):
class Meta:
exclude = ('type_detail', ) #right
答案 1 :(得分:0)
这真是令人费解。我恢复了forms.py的自动保存版本,它神奇地开始工作,但我可以辨别上面的代码片段和恢复的文件。
简短回答:“程序员错误”