这是我的观点:
def registerView(request):
form = RegistrationForm()
if request.method == 'POST':
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']
)
username=form.cleaned_data['username']
password=form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/home/')
variables = {'registerForm':form}
return render(request, 'register.html', variables)
这是我的RegistrationForm:
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(label='Password', widget=forms.PasswordInput())
password2 = forms.CharField(label='Confirm Password', 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):
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 ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
这是我的模板:
<form method="post" action="/regsiter/">{% csrf_token %}
<h6>username:</h6>
{{ registerForm.username }}
<h6>email</h6>
{{ registerForm.email }}
<h6>password:</h6>
{{ registerForm.password1 }}
<h6>confirm password:</h6>
{{ registerForm.password2 }}
<input type="hidden" name="next" />
<input type="submit" value="register" />
</form>
现在由于某种原因,当我转到我的模板并且没有填写任何内容(将所有字段留空)并尝试注册时,它会重定向到/ home /,这意味着它将表单标记为有效(如果form.is_valid ():由于某种原因返回true)即使所有字段都是空白。我甚至尝试使用存在的用户名,但它仍然表示该表单有效。知道为什么吗?
答案 0 :(得分:1)
表单操作拼写错误,因此从未触及registerView
。它应该是:
<form method="post" action="/register/">