0

表格.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  

模板.html

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

视图.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

用于验证电话号码字段。

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

谢谢

4

3 回答 3

3

在你的 model.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])
于 2020-01-30T15:33:20.103 回答
2

这里有很多问题。

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

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

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

第四,如果您出于充分的理由实际使用整数字段,则无需验证它们是否包含整数,因为 Django 已经自动执行此操作。如果由于某种原因您的模型字段不是整数字段,但您仍想验证为整数,只需覆盖表单中的字段定义:number1 = forms.IntegerField()

于 2013-05-07T09:05:54.150 回答
2

这应该有效。我会主动要求你阅读源代码,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))
于 2013-05-07T08:36:05.663 回答