我建议您彻底改变您对此的看法。在我看来,您应该在表单方面拥有所有实现。
forms.py
我已经实现了一个基于更完整的SetPasswordForm的类:
class EmailChangeForm(forms.Form):
"""
A form that lets a user change set their email while checking for a change in the
e-mail.
"""
error_messages = {
'email_mismatch': _("The two email addresses fields didn't match."),
'not_changed': _("The email address is the same as the one already defined."),
}
new_email1 = forms.EmailField(
label=_("New email address"),
widget=forms.EmailInput,
)
new_email2 = forms.EmailField(
label=_("New email address confirmation"),
widget=forms.EmailInput,
)
def __init__(self, user, *args, **kwargs):
self.user = user
super(EmailChangeForm, self).__init__(*args, **kwargs)
def clean_new_email1(self):
old_email = self.user.email
new_email1 = self.cleaned_data.get('new_email1')
if new_email1 and old_email:
if new_email1 == old_email:
raise forms.ValidationError(
self.error_messages['not_changed'],
code='not_changed',
)
return new_email1
def clean_new_email2(self):
new_email1 = self.cleaned_data.get('new_email1')
new_email2 = self.cleaned_data.get('new_email2')
if new_email1 and new_email2:
if new_email1 != new_email2:
raise forms.ValidationError(
self.error_messages['email_mismatch'],
code='email_mismatch',
)
return new_email2
def save(self, commit=True):
email = self.cleaned_data["new_email1"]
self.user.email = email
if commit:
self.user.save()
return self.user
此类检查电子邮件是否实际上已更改(例如,如果您需要验证电子邮件或更新邮件黑猩猩,这非常有用)并产生适当的错误,因此它们对表单视图中的用户很有帮助。
views.py
您的代码适合我的课程:
@login_required()
def email_change(request):
form = EmailChangeForm()
if request.method=='POST':
form = EmailChangeForm(user, request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/accounts/profile/")
else:
return render_to_response("email_change.html", {'form':form},
context_instance=RequestContext(request))
如您所见,视图被简化,确保了表单级别的所有内容。为了确保登录,我设置了一个装饰器(请参阅文档)。
Ps:我更改了email1
和email2
tonew_email1
并new_email2
与 Django 的密码方法保持一致。Email_Change_Form
我还根据EmailChangeForm
类的 Python 指南更改了表单。