我正在学习表单验证,如果我想在clean方法中同时验证name和money,似乎有很多错误,例如AttributeError,KeyError。
例如:
AttributeError at /learn/form_validate/
'NoneType' object has no attribute 'strip'
我的文件:
表格.py:
from django import forms
from django.core.exceptions import ValidationError
money_db = {
'Tom': 100,
'Jack': 200,
'Lucy': 300,
}
class ValidationForm(forms.Form):
name = forms.CharField(required=True)
money = forms.FloatField(required=True)
def clean_name(self):
name = self.cleaned_data.get('name').strip()
if not name in ['Tom', 'Jack', 'Lucy']:
raise ValidationError('No such person!')
return name
def clean(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get('name').strip() # AttributeError here
money = cleaned_data.get('money')
if money > money_db[name]:
raise ValidationError("You don't have so much money!")
return cleaned_data
视图.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import ValidationForm
def form_validate(request, template='learn/form_validate.html'):
form = ValidationForm()
if request.GET:
form = ValidationForm(request.GET)
if form.is_valid():
pass
context = RequestContext(request,{
'form': form,
})
return render_to_response(template, context)
html:
{% load staticfiles %}
<html>
<body>
<form action="">
<div>{{form.errors}}</div>
<div>Name: {{form.name}}</div>
<div>Money: {{form.money}}</div>
<input type="submit" value="Submit" />
</form>
</body>
</html>