我正在研究一个Django项目,似乎我不能在我的程序中的任何地方使用cleaned_data
模块。每次我使用它时,它都会引发一个关键错误(说密钥不存在),当我使用cleaned_data.get
时它就不会传递任何东西。我只能使用" form.data" (正如你在我的代码中看到的那样)并且一切正常。我只是想知道为什么我不能使用cleaning_data?
这是我的form.py:
class RegisterationForm(forms.Form):
first_name = forms.CharField
last_name = forms.CharField
username = forms.CharField
email = forms.EmailField
password = forms.CharField
password2 = forms.CharField
def clean(self):
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password and password != password2:
raise forms.ValidationError("passwords do not match")
return self.cleaned_data
这是我的view.py:
def注册(请求):
if request.method == 'POST':
form = RegisterationForm(request.POST)
if form.is_valid():
user_info={}
user_info['username'] = form.data['username']
user_info['first_name'] = form.data['first_name']
user_info['last_name'] = form.data['last_name']
user_info['password'] = form.data['password']
user_info['email']= form.data['email']
#salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
#usernamesalt = user_info['username']
#if isinstance(usernamesalt, unicode):
# usernamesalt = usernamesalt.encode('utf8')
user_info['activation_key'] = 1#hashlib.sha1(salt+usernamesalt).hexdigest()
form.sendEmail(user_info)
form.save(user_info)
return render_to_response('register_success.html',user_info)
else:
form_save = form
args = {}
args.update(csrf(request))
args['form'] = RegisterationForm()
return render_to_response('register.html',args)
答案 0 :(得分:2)
因为您没有调用父类clean
方法来获取数据:
def clean(self):
cleaned_data = super(RegisterationForm, self).clean()
password = cleaned_data.get('password')
password2 = cleaned_data.get('password2')
if password and password != password2:
raise forms.ValidationError("passwords do not match")
查看关于clean method的django doc。
答案 1 :(得分:0)
如果这确实是您的实际代码,那么您的表单没有任何字段,因为您没有调用任何字段定义。它应该是:
class RegisterationForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField()
password2 = forms.CharField()