我正在学习表单验证,如果我想在clean方法中同时验证名称和金钱,例如AttributeError,KeyError,那么似乎有很多错误。
e.g:
AttributeError at /learn/form_validate/
'NoneType' object has no attribute 'strip'
我的档案:
forms.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
views.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>
答案 0 :(得分:0)
您的clean_name
函数仅返回name
因此出现关键错误。您必须返回整个已清理的数据。看看https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
答案 1 :(得分:0)
def clean(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get('name') # if name is invalid, it is None
money = cleaned_data.get('money') # if money is invalid, it is None
if name and money: # make sure they are valid
if money > money_db[name]:
raise ValidationError("You don't have so much money!")
return cleaned_data