def is_valid(cpf): cpf_field = BRCPFField() try: cpf_field.clean(cpf) return True except ValidationError: return False
def clean_cpf(self): cpf = self.cleaned_data.get("cpf") if cpf: validador_cpf = BRCPFField() validador_cpf.clean(cpf) return cpf
def validate_cpf(number): number = as_digits(number) field = BRCPFField() try: field.clean(number) return number except ValidationError: raise CPFValidationError('Numero de CPF invalido - (%s)' % number)
class FormPurchase(CommonForm): insured_cpf = BRCPFField(label="CPF") insured_name = forms.CharField(max_length=100, label="Nome") birth_date = forms.DateField( label="Data de Nascimento", widget=forms.widgets.DateInput(attrs={'class': 'date'})) card_name = forms.CharField(max_length=100, label="Nome no cartão") card_cpf = BRCPFField(label="CPF") card_number = forms.CharField(max_length=16, label="Número do cartão") card_mouth = forms.ChoiceField(choices=( ('', '--'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10'), ('11', '11'), ('12', '12'), ), label="Validade mês") card_year = forms.ChoiceField(choices=( ('', '----'), ('2017', '2017'), ('2018', '2018'), ('2019', '2019'), ('2020', '2020'), ('2021', '2021'), ('2022', '2022'), ('2023', '2023'), ('2024', '2024'), ('2025', '2025'), ('2026', '2026'), ('2027', '2027'), ('2028', '2028'), ('2029', '2029'), ('2030', '2030'), ('2031', '2031'), ), label="Validade ano") card_cvv = forms.CharField(max_length=4, label="CVV") buy_name = forms.CharField(max_length=100, label="Nome para contato") buy_email = forms.EmailField(label="Email para contato") buy_phone = BRPhoneNumberField(label="Telefone para contato")
class RegisterPessoaFisica(forms.ModelForm): cpf = BRCPFField(required=True) class Meta: model = PessoaFisica fields = '__all__' #exclude = ['user']
class MemberForm(forms.ModelForm): cpf = BRCPFField(label=_("CPF"), required=True) phone = BRPhoneNumberField(label=_("Phone"), required=False) github_user = forms.CharField(label=_("GitHub User"), required=False) organization = forms.CharField(label=_("Organization"), widget=OrganizationInput, required=False) location = forms.CharField(label=_("Location"), required=False) class Meta: model = Member exclude = ('user', ) widgets = {'municipio': SelectMunicipioWidget} fields = ('category', 'github_user', 'organization', 'cpf', 'phone', 'address', 'location', 'municipio', 'relation_with_community', 'mailing', 'partner') def clean_organization(self): organization = self.cleaned_data['organization'] if not organization: return None organization_instance, created = Organization.objects.get_or_create( name=organization) return organization_instance def save(self, user, commit=True): self.instance.user = user return super(MemberForm, self).save(commit)
class UsuarioBuscarForm(forms.ModelForm): form_control_class = 'form-control ' nome = forms.CharField(widget=forms.TextInput(), required=False) perfil = forms.ModelChoiceField(Perfil.objects.all().order_by('nome'), required=False) ouvidoria = forms.ModelChoiceField( Orgao.objects.all().order_by('descricao'), required=False) status = forms.CharField(label="Status", widget=forms.Select(choices=GESTOR_STATUS), required=False) cpf = BRCPFField( max_length=14, min_length=1, error_messages={ 'invalid': 'Número do CPF inválido.', 'max_digits': 'Este campo requer no máximo 11 dígitos ou 14 caracteres.' }, required=False) def __init__(self, *args, **kwargs): super(UsuarioBuscarForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = self.form_control_class self.fields['cpf'].widget.attrs['class'] = 'form-control cpf' class Meta: model = UsuarioOrgao fields = '__all__' exclude = ('password', 'nome', 'email', 'orgao')
class PatientForm(ModelForm): # name = CharField(validators=[RegexValidator('^')]) gender = ChoiceField(choices=BOOL_CHOICES, label="Genêro", initial='', widget=Select(), required=True) name = CharField(label='Nome') birth_date = DateField(label='Data de Nascimento') phone = CharField(label='Telefone ou Celular') CPF = BRCPFField(label="CPF") RG = CharField(label='RG (Identidade)') class Meta: model = Patient # fields = ['name', 'gender', 'birth_date', 'email', 'phone', 'RG', 'CPF', 'comments', 'found_us_by', 'address'] # id = id_address name=id_address fields = '__all__' labels = { 'comments': 'Observações', 'found_us_by': 'Como nos encontrou' } widgets = { 'address': HiddenInput(), }
class TokensForm(ModelForm): cpf = BRCPFField(required=False, max_length=14, min_length=11) cnpj = BRCNPJField(required=False, min_length=16) cep = BRZipCodeField() class Meta: model = Headhunter fields = '__all__' labels = { 'address': 'Endereço', 'address2': '', } def __init__(self, *args, **kwargs): super(TokensForm, self).__init__(*args, **kwargs) # add custom error messages self.fields['cnpj'].error_messages.update({ 'invalid': 'CNPJ inválido', 'max_digits': 'CNPJ requer pelo menos 14 dígitos', }) self.fields['cpf'].error_messages.update({ 'invalid': 'CPF inválido', 'max_digits': 'CPF requer pelo menos 11 dígitos ou 14 caracteres', })
class CadastradorEnte(forms.ModelForm): cpf_cadastrador = BRCPFField() oficio_cadastrador = RestrictedFileField(widget=FileUploadWidget(), content_types=content_types, max_upload_size=max_upload_size) def __init__(self, *args, **kwargs): super(CadastradorEnte, self).__init__(*args, **kwargs) self.fields['oficio_cadastrador'].widget.attrs = { 'label': 'Ofício de Indicação do Cadastrador' } def clean_cpf_cadastrador(self): try: Usuario.objects.get( user__username=self.cleaned_data['cpf_cadastrador']) except Usuario.DoesNotExist: raise forms.ValidationError('Este CPF não está cadastrado.') return self.cleaned_data['cpf_cadastrador'] def save(self): sistema = self.instance cadastrador = Usuario.objects.get( user__username=self.cleaned_data['cpf_cadastrador']) sistema.cadastrador = cadastrador sistema.save() return sistema class Meta: model = SistemaCultura fields = ["cpf_cadastrador", "oficio_cadastrador"]
class TutorModelFormDisable(forms.ModelForm): _cpf = BRCPFField() _uf = forms.CharField(label='UF', max_length=20, required=False) def __init__(self, readonly_form=False, *args, **kwargs): super(TutorModelFormDisable, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['readonly'] = True self.fields['_uf'].widget.attrs['disabled'] = True class Meta: model = TutorEndTel fields = ('_nome', '_email', '_cpf', '_logradouro', '_numero', '_bairro', '_cidade', '_cep', '_uf', '_telefone1', '_telefone2') layout = Layout( Fieldset("Dados pessoais"), Row(Span2('_nome'), '_cpf'), Fieldset("Contato"), Row(Span2('_telefone1'), Span2('_telefone2'), Span2('_email')), Fieldset("Endereço"), Row(Span3('_logradouro'), '_numero'), Row(Span2('_bairro'), Span2('_cidade'), '_cep', ('_uf')), )
class TutorModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TutorModelForm, self).__init__(*args, **kwargs) for key, field in self.fields.items(): if isinstance(field.widget, forms.TextInput) or \ isinstance(field.widget, forms.Textarea) or \ isinstance(field.widget, forms.DateInput) or \ isinstance(field.widget, forms.DateTimeInput) or \ isinstance(field.widget, forms.TimeInput): field.widget.attrs.update({'placeholder': field.label}) _cpf = BRCPFField() class Meta: model = TutorEndTel fields = ('_nome', '_email', '_cpf', '_logradouro', '_numero', '_bairro', '_cidade', '_cep', '_uf', '_telefone1', '_telefone2') layout = Layout( Fieldset("Dados pessoais"), Row(Span2('_nome'), '_cpf'), Fieldset("Contato"), Row(Span2('_telefone1'), Span2('_telefone2'), Span2('_email')), Fieldset("Endereço"), Row(Span3('_logradouro'), '_numero'), Row(Span2('_bairro'), Span2('_cidade'), '_cep', ('_uf')), )
def __init__(self, *args, **kwargs): super(BaseCadastroPessoaForm, self).__init__(*args, **kwargs) self.fields['estado'] = BRStateChoiceField(initial="PR") self.fields['cpf'] = BRCPFField(required=False, label=_(u"CPF")) self.fields['cep'] = BRZipCodeField(required=False) self.fields['telefone'] = BRPhoneNumberField(required=False) self.fields['celular'] = BRPhoneNumberField(required=False)
class MoipWirecardCustomerForm(forms.Form): # personal informations email = forms.CharField() name = forms.CharField() last_name = forms.CharField() birth_date = forms.CharField(help_text='Padrão: aaaa-mm-dd') # cpf number_cpf = BRCPFField() # id_document number_rg = forms.CharField(help_text='Ex: Somente números') issuer = forms.CharField(help_text='Ex: Somente números') issue_date = forms.CharField() # phone informations country_code = forms.CharField(help_text='Código do País. Ex: 55') area_code = forms.CharField(help_text='Código do Estado. Ex: 11') phone_number = forms.CharField() # address informations street = forms.CharField() street_number = forms.CharField() district = forms.CharField() zip_code = forms.CharField(help_text='Ex: Somente números') city = forms.CharField() state = forms.CharField(help_text='Ex: Sigla do Estado.') def validate(self): if self.data.get('email') is None: raise forms.ValidationError( 'You cannot create a Wirecard without email')
class PersonForm(forms.ModelForm): cpf = BRCPFField(label=_(u'CPF')) def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['university'].required = True self.fields['course'].required = True self.fields['email'].required = True self.fields['city'].required = True if not self.instance: self.fields['cpf'].validators.append(cpf_is_unique) self.fields['email'].validators.append(email_is_unique) class Meta: model = Person fields = ('name', 'cpf', 'email', 'email', 'city', 'university', 'course', 'semester', 'facebook', 'twitter') widgets = { 'kind': forms.HiddenInput(), 'facebook': forms.URLInput( attrs={ 'placeholder': 'Ex.: https://facebook.com/cleandev.org' }), 'twitter': forms.URLInput( attrs={'placeholder': 'Ex.: https://twitter.com/cleandev'}) }
class UserAdminCreationForm(UserCreationForm): cpf = BRCPFField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'name', 'cpf', 'gender', 'telephone', 'birth']
class RegisterForm(forms.ModelForm): cnpj = BRCNPJField(label='CNPJ', required=False) cpf = BRCPFField(label='CPF', required=False) password = forms.CharField(label='Senha', max_length=36, widget=forms.PasswordInput, required=True) class Meta: model = Registration fields = [ 'username', 'password', 'name', 'cnpj', 'cpf', 'phone', 'email' ] def clean_name(self): name = self.cleaned_data['name'] words = [w.capitalize() for w in name.split()] return ' '.join(words) def clean(self): self.cleaned_data = super().clean() if not self.cleaned_data.get('phone') and not self.cleaned_data.get( 'email'): raise ValidationError('Informe seu telefone ou e-mail.') if not self.cleaned_data.get('cpf') and not self.cleaned_data.get( 'cnpj'): raise ValidationError('Informe seu cpf ou cnpj.') return self.cleaned_data
class VoluntarioForm(forms.ModelForm): cpf = BRCPFField( required=True, widget=forms.TextInput(attrs={'placeholder': '___.___.___.___-__'})) class Meta: model = Voluntario fields = ['cpf', 'sexo']
class MoipWirecardCompanyForm(forms.Form): email = forms.CharField() name_person = forms.CharField(help_text='Nome do Representante') birth_date = forms.CharField(help_text='Padrão: aaaa-mm-dd') # cpf number_cpf = BRCPFField(help_text='Somente Números') # phone informations country_code_personal = forms.CharField(help_text='Código do País. Ex: 55') area_code_personal = forms.CharField(help_text='Código do Estado. Ex: 11') phone_number_personal = forms.CharField() # address informations street_personal = forms.CharField() street_number_personal = forms.CharField() district_personal = forms.CharField() zip_code_personal = forms.CharField(help_text='Ex: Somente números') city_personal = forms.CharField() state_personal = forms.CharField(help_text='Ex: Sigla do Estado.') # Company Informations name_company = forms.CharField(help_text='Nome Fantasia') business_name = forms.CharField(help_text='Razão social') opening_date = forms.CharField(help_text='Padrão: aaaa-mm-dd') # CNPJ number_cnpj = BRCNPJField() # CNAE Informations cnae = forms.CharField( help_text='Código CNAE de atividade. Exemplo 82.91-1/00') description = forms.CharField( help_text= 'Descrição da atividade. Exemplo: Atividades de cobranças e informações cadastrais' ) # Phone informations country_code_company = forms.CharField(help_text='Código do País. Ex: 55') area_code_company = forms.CharField(help_text='Código do Estado. Ex: 11') phone_number_company = forms.CharField() # Address informations street_company = forms.CharField() street_number_company = forms.IntegerField() district_company = forms.CharField() zip_code_company = forms.CharField(help_text='Ex: Somente números') city_company = forms.CharField() state_company = forms.CharField(help_text='Ex: Sigla do Estado.') def validate(self): if self.data.get('email') is None: raise forms.ValidationError( 'You cannot create a Wirecard without email')
class ClientForm(forms.ModelForm): class Meta: model = Client form = Client widgets = {'state': BRStateSelect(), 'country': CountrySelectWidget()} fields = ['name', 'cpf', 'phone', 'cep', 'cnpj', 'state'] cpf = BRCPFField() cep = BRZipCodeField(required=True) cnpj = BRCNPJField(label='CNPJ', required=False) phone = BRPhoneNumberField(label='Telefone')
class AttendeeForm(forms.ModelForm): cpf = BRCPFField(required=False, help_text=_('Optional. Numbers only. Only if you wish to add this information in ' 'the certificate.')) authorize = forms.BooleanField(required=True, label=_('I authorize the use of my data exclusively for my ' 'identification at this PotiLivre event.')) share_data_with_partners = forms.BooleanField(label=_('I also authorize to share my name and e-mail information ' 'with PotiLivre partners.'), required=False) class Meta: model = Attendee fields = ('name', 'email', 'cpf', 'authorize', 'share_data_with_partners')
class CadastroForm(forms.ModelForm): cpf = BRCPFField(max_length=11, min_length=11) class Meta: model = Cadastro fields = [ 'senha', 'nome', 'cpf', 'email' ]
class CadastrarGestor(ModelForm): cpf = BRCPFField() termo_posse = RestrictedFileField(content_types=content_types, max_upload_size=52428800) rg_copia = RestrictedFileField(content_types=content_types, max_upload_size=52428800) cpf_copia = RestrictedFileField(content_types=content_types, max_upload_size=52428800) class Meta: model = Gestor exclude = ('tipo_funcionario', )
class UsuarioCompletoForm(forms.ModelForm): cpf = BRCPFField(label='Seu CPF', required=True) class Meta: model = Usuario fields = ['email', 'nome', 'cpf', 'telefone_ddd', 'telefone_numero'] def clean_nome(self): nome = self.cleaned_data.get('nome') if len(nome.split(' ')) == 1: raise ValidationError('Utilize seu nome e sobrenome', code='invalid') return nome
class UserCreation(UserCreationForm): cpf = BRCPFField(label='CPF') class Meta: model = User fields = ['username', 'nome', 'email', 'cpf'] def __init__(self, *args, **kwargs): super(UserCreation, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label
class FormCliente(forms.ModelForm): cpf = BRCPFField(widget=CPFInput, label='CPF') telefone = BRPhoneNumberField(widget=BRPhoneNumberInput, required=False) def clean_telefone(self): value = self.cleaned_data['telefone'] value = re.sub('-', '', smart_text(value)) if value == '': return None else: return int(value) class Meta: model = Cliente fields = ['nome', 'sobrenome', 'cpf', 'codigo', 'sexo', 'estado_civil','telefone',]
class CadastrarUsuarioForm(UserCreationForm): username = BRCPFField() confirmar_email = forms.EmailField(required=True) email = forms.EmailField(required=True) nome_usuario = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'password1', 'password2') def clean_confirmar_email(self): if self.data.get('email') != self.cleaned_data['confirmar_email']: raise forms.ValidationError('Confirmação de e-mail não confere.') return self.cleaned_data['confirmar_email'] def clean_email(self): usuarios = User.objects.filter(email=self.cleaned_data['email']) if not usuarios: return self.cleaned_data['email'] else: raise forms.ValidationError('Este e-mail já foi cadastrado!') def clean_username(self): try: User.objects.get(username=''.join( re.findall('\d+', self.cleaned_data['username']))) raise forms.ValidationError('Esse CPF já foi cadastrado.') except User.DoesNotExist: return self.cleaned_data['username'] return self.cleaned_data['username'] def save(self, commit=True): user = super(CadastrarUsuarioForm, self).save(commit=False) user.username = limpar_mascara(self.cleaned_data['username']) user.email = self.cleaned_data['email'] user.is_active = False if commit: user.save() usuario = Usuario() usuario.user = user usuario.nome_usuario = self.cleaned_data['nome_usuario'] codigo_ativacao = get_random_string() usuario.codigo_ativacao = codigo_ativacao if commit: usuario.save() return user
class FormUsuario(forms.ModelForm): error_messages = { 'password_mismatch': _("The two password fields didn't match."), } cpf = BRCPFField(widget=CPFInput, label='CPF') telefone = BRPhoneNumberField(widget=BRPhoneNumberInput, required=False) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as before, for verification.")) def __init__(self, *args, **kwargs): super(FormUsuario, self).__init__(*args, **kwargs) self.fields['cpf'].widget.attrs.update({'autofocus': ''}) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) self.instance.cpf = self.cleaned_data.get('cpf') password_validation.validate_password(self.cleaned_data.get('password2'), self.instance) return password2 def save(self, commit=True): user = super(FormUsuario, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user def clean_telefone(self): value = self.cleaned_data['telefone'] value = re.sub('-', '', smart_text(value)) if value == '': return None else: return int(value) class Meta: model = Usuario fields = ['cpf', 'nome', 'sobrenome', 'tipo', 'codigo', 'email', 'telefone', 'nascimento',]
class PerfilForm(forms.ModelForm): first_name = forms.CharField(label='Primeiro nome') last_name = forms.CharField(label='Último nome') cpf = BRCPFField(label='CPF') data_nascimento = forms.DateField() sexo = forms.ChoiceField(label='Sexo', choices=tipo_sexo) class Meta: model = User fields = ('first_name', 'last_name', 'email',) def __init__(self, *args, **kwargs): super(PerfilForm, self).__init__(*args, **kwargs) self.fields['cpf'].widget.attrs['class'] = 'form-control cpf' self.fields['data_nascimento'].widget.attrs['class'] = 'form-control date'
class MemberForm(forms.ModelForm): cpf = BRCPFField(label=_("CPF"), required=True) phone = BRPhoneNumberField(label=_("Phone"), required=False) github_user = forms.CharField(label=_("GitHub User"), required=False) organization = forms.CharField(label=_("Organization"), widget=OrganizationInput, required=False) location = forms.CharField(label=_("Location"), required=False) class Meta: model = Member exclude = ('user', ) widgets = {'municipio': SelectMunicipioWidget} fields = ('category', 'github_user', 'organization', 'cpf', 'phone', 'address', 'location', 'municipio', 'relation_with_community', 'mailing', 'partner') def __init__(self, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) # if self.instance: # if not self.instance.get_payment_status(): # self.fields['category'].widget.attrs['disabled'] = 'disabled' def clean_category(self): category = self.cleaned_data['category'] if self.instance.id: if not self.instance.get_payment_status(): if self.instance.category != category: raise forms.ValidationError( _("You can't change your category with pending payments" )) return category def clean_organization(self): organization = self.cleaned_data['organization'] if not organization: return None organization_instance, created = Organization.objects.get_or_create( name=organization) return organization_instance def save(self, user, commit=True): self.instance.user = user return super(MemberForm, self).save(commit)
class FormResponsavel(forms.Form): nome = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'class': 'form-control'})) pai = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'class': 'form-control'})) mae = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'class': 'form-control'})) cpf = BRCPFField(widget=forms.TextInput(attrs={'class': 'form-control'})) rg = forms.CharField(max_length=25, widget=forms.TextInput(attrs={'class': 'form-control'})) org_expedidor = forms.CharField(max_length=10, widget=forms.TextInput(attrs={'class': 'form-control', 'pattern': '\w{3,5}\/\w{2}'})) data_nascimento = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'})) rua = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'class': 'form-control'})) numero = forms.CharField(max_length=10, widget=forms.TextInput(attrs={'class': 'form-control'})) bairro = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'class': 'form-control'})) cidade = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) estado = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'class': 'form-control'})) tel_principal = forms.CharField(max_length=16, widget=forms.TextInput(attrs={'class': 'form-control'})) tel_alternativo = forms.CharField(max_length=16, widget=forms.TextInput(attrs={'class': 'form-control'})) tipo_vida = forms.ChoiceField(set((c.id, c.nome) for c in TipoVida.objects.all()), widget=forms.Select(attrs={'class': 'form-control'})) escolaridade = forms.ChoiceField(set((x.id, x.nome) for x in Escolaridade.objects.all()), widget=forms.Select(attrs={'class': 'form-control'}))