1

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))

Getting the below traceback

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

For validating the phone number field.

Condition is it should take only numeric digits,should not take alphabet or alpha-numeic,the above code not producing any errors not validation is not happening.What went wrong in my code.

Thanks

4
  • Why are you returning the numbers? Commented May 7, 2013 at 6:30
  • sorry,i removed,but why the validation is not happening Commented May 7, 2013 at 6:36
  • You could use the inbuilt validators. Use RegexValidator against \d+. docs.djangoproject.com/en/dev/ref/validators/#regexvalidator Commented May 7, 2013 at 6:38
  • Post your view code, and fix your indentation. Commented May 7, 2013 at 6:38

4 Answers 4

4

Use this in your 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])
Sign up to request clarification or add additional context in comments.

2 Comments

the regex should be r'^[0-9]+' which means any digit character of any length
another option is r'^\d+'
3

This should work. And I'd actively request you to read the source of validate_integer() and see what they did there.

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))

Comments

2

Lots of issues here.

Firstly, you should not store phone numbers as integers. Integer fields don't allow brackets, dashes, leading zeroes, and all sorts of other things that phone numbers do.

Secondly, your clean method must return self.cleaned_data at the end, which is the source of your actual problem.

Thirdly, you should do individual field validation in the clean_FIELDNAME methods - eg clean_number1 etc.

Fourthly, if you were actually using integer fields for a good reason, there is no need to validate that they contain integers, because Django does that automatically already. If for some reason your model field is not an integerfield but you still want to validate as an integer, just override the field definition in your form: number1 = forms.IntegerField().

1 Comment

5th: if a phone number start with 0 and you store it using an integer field, the leading zero/s (phone number prefix) are lost
0

For phone numbers you should control number possiblity with accuracy. In example if your phone numbers are similar to abccccccccc which a is always zero, b is not zero and c can be any digits while total length is exactly eleven digits. You should have a regex which start with zero (^0) after that one none zero digit ([1-9]) and then exactly nine other digits (\d{9}) not more ($).

from django import forms
from django.core.validators import RegexValidator

class MyForm(forms.Form):
    phone_validator = RegexValidator("^0[1-9]\d{9}$")
    mobile = forms.CharField(
        validators=(phone_validator,),)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.