From 34d6ebe7d1335370b1639be38090fab2018f9f01 Mon Sep 17 00:00:00 2001 From: ailsoncgt Date: Wed, 28 Sep 2016 16:33:43 -0300 Subject: [PATCH] Validate cpf in forms.py #14 --- core/forms.py | 38 +++++++++++++++++++++++++++++++++++++- requirements.txt | 6 ++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/core/forms.py b/core/forms.py index 8557677..800d408 100644 --- a/core/forms.py +++ b/core/forms.py @@ -1,6 +1,10 @@ from django import forms from django.utils.translation import ugettext_lazy as _ from users.models import User +from pycpfcnpj import cpfcnpj +import re + + class RegisterUserForm(forms.ModelForm): @@ -9,6 +13,37 @@ class RegisterUserForm(forms.ModelForm): # birth_date = forms.DateField(widget=forms.SelectDateWidget()) MIN_LENGTH = 8 + def validate_cpf(self, cpf): + cpf = ''.join(re.findall('\d', str(cpf))) + # print(cpf) + + # if (not cpf) or (len(cpf) < 11): + # return False + + # #Get only the first 9 digits and generate other 2 + # _int = map(int, cpf) + # integer = list(map(int, cpf)) + # new = integer[:9] + + # while len(new) < 11: + # r = sum([(len(new) + 1 - i)* v for i, v in enumerate(new)]) % 11 + + # if r > 1: + # f = 11 - r + # else: + # f = 0 + # new.append(f) + + # #if generated number is the same(original) the cpf is valid + # new2 = list(new) + # if new2 == _int: + # return cpf + # else: + # return False + if cpfcnpj.validate(cpf): + return True + return False + def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email = email).exists(): @@ -19,7 +54,8 @@ class RegisterUserForm(forms.ModelForm): cpf = self.cleaned_data['cpf'] if User.objects.filter(cpf = cpf).exists(): raise forms.ValidationError(_('There is already a registeres User with this CPF')) - print(cpf) + if not self.validate_cpf(cpf): + raise forms.ValidationError(_('Please enter a valid CPF')) return cpf def clean_password(self): diff --git a/requirements.txt b/requirements.txt index ee6d8d5..cbf4ba6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ click==6.6 +deps==0.1.0 Django==1.10 -django-autoslug==1.9.3 django-bootstrap-breadcrumbs==0.8 django-discover-runner==1.0 django-role-permissions==1.2.1 @@ -10,6 +10,8 @@ itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 Pillow==3.3.1 -psycopg2==2.6.2 +pkg-resources==0.0.0 +pycpfcnpj==1.0.2 six==1.10.0 +slugify==0.0.1 Werkzeug==0.11.11 -- libgit2 0.21.2