2012-12-17 53 views
0

在我的form.py中,我收到以下錯誤(下面)是否有任何我錯過了可以向我解釋的錯誤?所有我想要做清潔/驗證確認密碼字段Django Forms:KeyError試圖驗證貓頭鷹

這是錯誤:

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

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

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

回答

3

如果你想檢查兩個領域的表格,你應該在clean()方法中做到這一點,而不是單個領域的清潔方法。

您看到的問題是,在clean_password方法中,cleaned_data不包含'passwordConfirm'的值。即其清潔方法 - clean_passwordConfirm()尚未被調用。

Cleaning and validating fields that depend on each other

示例代碼文檔:

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

,所以我創建一個新的高清乾淨(個體經營):在forms.py並添加功能中的兩個clean_username和clean_password? – Prometheus

+0

你不需要在函數中添加你的方法,但是寫'clean(self)'來檢查兩個字段是相同的。查看示例代碼。 – Rohan