简体   繁体   English

Django Forms:尝试验证猫科动物时出现KeyError

[英]Django Forms: KeyError when trying to validate felid

In my form.py I'm getting the following error (below) is there anything I have missed that could be explained to me? 在我的form.py中,我收到以下错误(如下),我错过了什么可以向我解释的东西吗? All I'm trying to do it clean/validate the confirm password field 我正在尝试清除/验证确认密码字段

This is the error: 这是错误:

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

forms.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

models.py models.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)

view.py view.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))

If you want to check form for two fields you should do that in clean() method rather than individual fields clean method. 如果要检查两个字段的表单,则应使用clean()方法而不是单个字段的clean方法。

Problem that you are seeing is, while you are in clean_password method, cleaned_data do not contain value for 'passwordConfirm' . 您看到的问题是,当您使用clean_password方法时, cleaned_data不包含'passwordConfirm'值。 ie its clean method - clean_passwordConfirm() is not called yet. 即它的清洁方法clean_passwordConfirm()尚未被调用。

Documentation at Cleaning and validating fields that depend on each other 相互依赖的清理和验证字段中的文档

Sample code: 样例代码:

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.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM