我正在制作用户注册表单。这是我的模板的样子:
<h1>Register</h1>
<form action="/register/" method="post">
{{ form.as_p }}
<input type="submit" value="Register">
</form>
这是我的观点:
from djangoproject1.authentication import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def main(request):
rform = forms.RegisterForm()
return render_to_response("authentication/index.html", {'form': rform})
def register(request):
if request.method == 'POST':
rform = forms.RegisterForm(request.POST)
if rform.is_valid():
print 'VALID!'
# do something
return HttpResponseRedirect("/register-success/")
else:
print 'INVALID!'
rform = forms.RegisterForm()
return render_to_response("authentication/index.html", {'form': rform})
我还没有进入VALID部分,我还在处理无效部分。这是我的表单:
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(min_length=6,max_length=15)
password = forms.CharField(widget = forms.PasswordInput(),min_length=6,max_length=15)
confirm_password = forms.CharField(widget = forms.PasswordInput(),min_length=6,max_length=15)
phone_number = forms.RegexField('\d\d\d-\d\d\d-\d\d\d\d',error_message='Invalid format')
def clean_password(self):
password = self.cleaned_data['password']
confirm_password = self.cleaned_data['confirm_password']
if password != confirm_password:
raise forms.ValidationError("Passwords don't match")
return password
用户名,密码,电话号码。非常直截了当。但是,当我点击“注册”而没有填写任何内容时,我应该得到一堆错误,但它们不会出现在任何地方。这应该是自动发生还是我遗失了什么?
谢谢!
答案 0 :(得分:2)
我认为您的问题是,在您的其他地方,您正在将表单重置为新表单,并且新表单尚未经过验证。尝试从您的其他地方删除这行代码
rform = forms.RegisterForm()