我有一张注册表。当我尝试注册时,确实如此,一切都很好,就是这样,它现在显示模板中的任何表单验证错误,应该有。
forms.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.')
views.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)
register.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 %}
但没有运气。我想我错过了什么。
答案 0 :(得分:3)
原因是,如果有错误,则用form=UserCreationForm()
基本上,如果if form.is_valid()
为False
,则您需要不加改变地发送表单。通过在 form=UserCreationForm
之后调用form.is_valid()
,您将覆盖错误
试试这个:
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
else:
form = UserCreationForm()
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))