class PessoaForm(ModelForm): telefone = BRPhoneNumberField() celular = BRPhoneNumberField(required=False) cpf = BRCPFField(label='CPF') usuario = forms.RegexField( label=_("Username"), max_length=30, regex=r'^\w+$', help_text= _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)." ), error_message=_( "This value must contain only letters, numbers and underscores.")) def save(self, *args, **kwargs): if not self.instance.id: u = User.objects.create_user(self.data.get('usuario'), self.data.get('email'), '123456') tipo = self.data.get('tipo') if tipo == '2': grupo = Group.objects.filter(name='Professores') u.groups.add(grupo[0]) elif tipo == '3': grupo = Group.objects.filter(name='Alunos') u.groups.add(grupo[0]) u.is_staff = True u.save() self.instance.user = u return super(PessoaForm, self).save(*args, **kwargs) class Meta: model = Pessoa exclude = ('user')
class UsuarioForm(ModelForm): telefone = BRPhoneNumberField( label='Telefone', help_text=u'Digite um número válido no formato xx-xxxx-xxxx.') class Meta: model = Usuario
class EntryForm(forms.ModelForm): phone = BRPhoneNumberField(label="Telefone", help_text="Exemplo: XX-XXXX-XXXX") mobile = BRPhoneNumberField(label="Celular", help_text="Exemplo: XX-XXXX-XXXX") cpf = BRCPFField(label="CPF", help_text="Exemplo: XXX.XXX.XXX-VD") class Meta: model = Entry widgets = { 'poster_abstract': forms.Textarea(attrs={ 'cols': 54, 'rows': 20 }), }
class FormAvaliado(ModelForm): referencia = forms.CharField() cep = BRZipCodeField(label='CEP') turma = forms.CharField() estado = BRStateChoiceField(label='Estado') cpf = BRCPFField(label='CPF', required=False) foneresidencial = BRPhoneNumberField(label='Telefone') class Meta: model = Avaliado
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', ) fields = ('category', 'github_user', 'organization', 'cpf', 'phone', 'address', 'location', '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 ClienteForm(ModelForm): telefone = BRPhoneNumberField(label='Telefone', required=False, help_text=u'Ex.: 00-0000-0000') celular = BRPhoneNumberField(label='Celular', required=False, help_text=u'Ex.: 00-0000-0000') class Meta: model = Cliente
class FornecedorForm(forms.ModelForm): class Meta: model = Fornecedor telefone = BRPhoneNumberField(help_text="o campo deve ser preenchido da seguinte maneira: xxxxxxxxxx") fax = BRPhoneNumberField(help_text="o campo deve ser preenchido da seguinte maneira: xxxxxxxxxx")
class PessoaForm(ModelForm): telefone = BRPhoneNumberField(help_text = _("Formato de telefone xx-xxxx-xxxx ")) celular = BRPhoneNumberField(required=False,help_text = _("Formato de celular xx-xxxx-xxxx ")) cpf = BRCPFField(label='CPF',required=False) estado = BRStateChoiceField(initial = 'AL') naturalidade_estado = BRStateChoiceField(label='Estado',initial='AL') usuario = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$', help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."), error_message = _("This value must contain only letters, numbers and underscores.")) def __init__(self, *args, **kwargs): self.base_fields['data_nascimento'].widget = SelectDateWidget() super(PessoaForm, self).__init__(*args, **kwargs) def clean_usuario(self): queryset = User.objects.filter(username=self.cleaned_data['usuario']) if self.instance.id: queryset = queryset.exclude(pk=self.instance.user.id) if len(queryset) == 0: return self.cleaned_data['usuario'] raise forms.ValidationError(u'Nome de usuário já cadastrado. Escolha outro.') def clean_rg(self): rg = self.cleaned_data['rg'] if rg not in EMPTY_VALUES: try: int(rg) except ValueError: raise forms.ValidationError(u'O RG deve conter apenas números') length = len(rg) if length < 6: raise forms.ValidationError(u'Certifique-se de que o valor tenha mais que \ 7 caracters (ele possui %d)' % length) queryset = Pessoa.objects.filter(rg=self.cleaned_data['rg']) if len(queryset) == 0: return self.cleaned_data['rg'] raise forms.ValidationError(u'Já existe uma Pessoa Física cadastrada com o RG: %s' % rg) def save(self, *args, **kwargs): if not self.instance.id: try: user = User.objects.get(username=self.data.get('usuario')) except User.DoesNotExist: user = [] if user : self.instance.user = user else: u = User.objects.create_user(self.data.get('usuario'), self.data.get('email'), '123456') tipo = self.data.get('tipo') if tipo =='1': grupo = Group.objects.filter(name='Administrador') u.groups.add(grupo[0]) elif tipo == '2': grupo = Group.objects.filter(name='Caixa') u.groups.add(grupo[0]) elif tipo == '3': grupo = Group.objects.filter(name='Cliente') u.groups.add(grupo[0]) else: grupo = Group.objects.filter(name='Entregador') u.groups.add(grupo[0]) u.save() self.instance.user = u else: self.instance.user.groups.clear() tipo = self.data.get('tipo') if tipo =='1': grupo = Group.objects.filter(name='Administrador') self.instance.user.groups.add(grupo[0]) elif tipo == '2': grupo = Group.objects.filter(name='Caixa') self.instance.user.groups.add(grupo[0]) elif tipo == '3': grupo = Group.objects.filter(name='Cliente') self.instance.user.groups.add(grupo[0]) else: grupo = Group.objects.filter(name='Entregador') self.instance.user.groups.add(grupo[0]) self.instance.user.save() return super(PessoaForm,self).save(*args, **kwargs) class Meta: model = Pessoa exclude = ('user')