我有一个注册表格。当我尝试注册时,它确实可以,一切都很好,只是,它现在在模板中显示任何表单验证错误,当应该有的时候。
表格.py:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
import re
from django.core.exceptions import ObjectDoesNotExist
class UserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'username',)
username = forms.EmailField(label='Email', max_length=250)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = user.username
user.save()
return user
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('Password do not match.')
def clean_username(self):
username = self.cleaned_data['username']
if not re.search(r'^\w[\w.]*@[\w.]+$', username):
raise forms.ValidationError('Please enter a valid email address.')
try:
User.objects.get(username=username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Email address is already taken.')
视图.py:
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
print form.is_valid()
print form.errors
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
print args
return render_to_response('register.html', args)
注册.html:
{% extends "base.html" %}
{% block content %}
<h1>Registration:</h1>
<form method="post" action=".">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Register" />
</form>
{% endblock %}
我什至尝试过{% if form.errors %}
:
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p>{{form.errors }}</p>
{% endif %}
<h1>Registration:</h1>
<form method="post" action=".">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Register" />
</form>
{% endblock %}
但没有运气。我想我错过了一些东西。