0

我正在学习表单验证,如果我想在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>
4

2 回答 2

0

您的clean_name函数只返回name关键错误。您必须返回整个清理后的数据。看看这里https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

于 2013-09-16T09:28:49.413 回答
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
于 2013-09-16T13:52:22.063 回答