django中表单中的数字验证

时间:2013-05-07 06:26:50

标签: django django-models django-forms django-templates

forms.py

class PhoneForm(forms.ModelForm):

    fields = ['user','name1','number1','name2','number2','name3','number3','emergency','emergency_number']
def clean(self):
        cd=self.cleaned_data
        number1=cd.get('number1')
        number2=cd.get('number2')
        number3=cd.get('number3')

        if (number1.isalpha()):
            raise forms.ValidationError("Please enter a valid phone number")
        return number1

        if(number2.isalpha()): 
            raise forms.ValidationError("Please enter a valid phone number")
        return number2   

        if(number3.isalpha()): 
            raise forms.ValidationError("Please enter a valid phone number")
        return number3  

template.html

            <tr>
                <td>{{PhoneForm.name1}}</td>
                <td>{{PhoneForm.number1}}{{ PhoneForm.number1.errors }}</td>
            </tr>

views.py

def add_phone(request):

    phoneForm = PhoneForm({'user':request.user}) 
    phone = Phone_info.objects.get(user=request.user)
    phoneForm = PhoneForm(instance=phone) 
    if request.method=='POST':   
        phoneForm = PhoneForm(request.POST,instance=phone)
        if phoneForm.is_valid():
            phone=phoneForm.save(commit=False)
            phone.save()
            return redirect('/member/contact-list/')

    return render_to_response('incident/add_phone.html',
    {
    'about_menu': True,
    'PhoneForm' :phoneForm
    },
    context_instance=RequestContext(request))

获取以下追溯

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/root/Projects/ir/incident/views.py" in add_phone
  634.         if phoneForm.is_valid():
File "/usr/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  121.         return self.is_bound and not bool(self.errors)
File "/usr/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  112.             self.full_clean()
File "/usr/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  269.         self._post_clean()
File "/usr/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
  308.         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "/usr/lib/python2.7/site-packages/django/forms/models.py" in construct_instance
  39.                 or not f.name in cleaned_data:

Exception Type: TypeError at /member/add-phone/
Exception Value: argument of type 'NoneType' is not iterable

用于验证电话号码字段。

条件是它应该只采用数字,不应该采用字母或字母数字,上面的代码不会产生任何错误而不会发生验证。我的代码出了什么问题。

由于

3 个答案:

答案 0 :(得分:2)

这应该有效。我会主动要求你阅读the source of validate_integer(),看看他们在那里做了什么。

from django.core.validators import validate_integer

class PhoneForm(forms.ModelForm):
    fields = ['user','name1','number1','name2','number2','name3','number3','emergency','emergency_number']

    def clean(self):
        cd=self.cleaned_data
        validate_integer(cd.get('number1', None))
        validate_integer(cd.get('number2', None))
        validate_integer(cd.get('number3', None))

答案 1 :(得分:2)

这里有很多问题。

首先,您应该将电话号码存储为整数。整数字段不允许括号,破折号,前导零以及电话号码所做的各种其他事情。

其次,您的clean方法最后必须返回self.cleaned_data,这是您实际问题的根源。

第三,您应该在clean_FIELDNAME方法中进行单独的字段验证 - 例如clean_number1等。

第四,如果你实际上使用整数字段是有充分理由的,那么就没有必要验证它们是否包含整数,因为Django已经自动完成了。如果由于某种原因,您的模型字段不是整数字段,但您仍希望验证为整数,则只需覆盖表单中的字段定义:number1 = forms.IntegerField()

答案 2 :(得分:1)

在模型中使用它。py

from django.core.validators import RegexValidator

numeric = RegexValidator(r'^[0-9+]', 'Only digit characters.')

class FooModel(models.Model):
    phone = models.CharField(max_length=500, blank=True, validators=[numeric])