0

在我的 form.py 中,我收到以下错误(如下)有什么我错过的可以向我解释的吗?我正在尝试清理/验证确认密码字段

这是错误:

KeyError at /member/registration/
'passwordConfirm'

response = callback(request, *callback_args, **callback_kwargs)

Users/user/Documents/workspace/project/member/forms.py in clean_password, line 27

表格.py

def clean_password(self):
    password = self.cleaned_data['password']
    passwordConfirm = self.cleaned_data['passwordConfirm']
    if password != passwordConfirm:
        raise forms.ValidationError("Password does not match, try again.")
    return password
    strong text

模型.py

from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User


class Member (models.Model):
    user =  models.OneToOneField(User)
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

def createUserCallBacks(sender, instance, **kwargs):
    member, new = Member.objects.get_or_create(user=instance)
post_save.connect(createUserCallBacks, User)

视图.py

def registration(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/error')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email'], password=form.changed_data['password'])
            user.save()
            member = User.get_profile()
            member.name = form.cleaned_data['name']
            member.save()
            return HttpResponseRedirect('/profile')
        else:
            return render_to_response('pageRegistration.html', {'form':form},context_instance=RequestContext(request))

    else: 
        form = RegistrationForm 
        context = {'form':form}
        return render_to_response('pageRegistration.html', context, context_instance=RequestContext(request))
4

1 回答 1

3

如果您想检查两个字段的表单,您应该在clean()方法中而不是单个字段的清理方法中执行此操作。

您看到的问题是,当您使用clean_password方法时,cleaned_data不包含'passwordConfirm'. 即它的干净方法 -clean_passwordConfirm()尚未调用。

清理和验证相互依赖的字段中的文档

示例代码:

def clean(self):
    try:
        cleaned_data = super(RegistrationForm, self).clean()
        password = cleaned_data['password']
        passwordConfirm = cleaned_data['passwordConfirm']
        if password != passwordConfirm:
            raise forms.ValidationError("Password does not match, try again.")
        return cleaned_data
    except:
        raise forms.ValidationError("Password does not match, try again.")
于 2012-12-17T10:04:15.153 回答