class UpdateUserForm(forms.Form): first_name = forms.CharField( max_length=128, required=True, label="Nome", widget=forms.TextInput(attrs={'placeholder': 'Seu nome...'})) last_name = forms.CharField( max_length=128, required=True, label="Sobrenome", widget=forms.TextInput(attrs={'placeholder': 'Seu sobrenome...'})) email = forms.EmailField(required=True, label="Email") current_password = forms.CharField( required=True, label="Senha Atual", widget=forms.PasswordInput(attrs={ 'placeholder': 'Sua senha...', 'render_value': False })) layout = Layout(Row('first_name', 'last_name'), 'email', 'current_password')
class OrderForm(forms.Form): name = forms.CharField() company = forms.CharField() email = forms.EmailField() phone = forms.CharField() interest = forms.ChoiceField(choices=((None, 'Interested in'), ('D', 'Design'), ('C', 'Development'), ('I', 'Illustration'), ('B', 'Branding'), ('V', 'Video'))) budget = forms.ChoiceField(choices=((None, 'Budget'), ('S', 'Less than $5000'), ('M', '$5000-$10000'), ('L', '$10000-$20000'), ('XL', 'More than $20000'))) start_date = forms.DateField(label="Expected start date") finish_date = forms.DateField(label="Expected finish date") attachment = forms.FileField(label="Include some file...") message = forms.CharField(widget=forms.Textarea) layout = Layout('name', 'company', 'email', 'phone', Row('interest', 'budget'), Row('start_date', 'finish_date'), 'attachment', 'message') template = Template(""" {% form %} {% part form.name prefix %}<i class="mdi-action-account-box prefix"></i>{% endpart %} {% part form.company prefix %}<i class="mdi-communication-business prefix"></i>{% endpart %} {% part form.email prefix %}<i class="mdi-communication-email prefix"></i>{% endpart %} {% part form.phone prefix %}<i class="mdi-communication-call prefix"></i>{% endpart %} {% endform %} """) buttons = Template(""" <button class="btn btn-primary pull-right" type="submit">Submit request</button> """) title = "Order services"
class RegistrationForm(forms.Form): username = forms.CharField() email = forms.EmailField(label="Email Address") password = forms.CharField(widget=forms.PasswordInput) password_confirm = forms.CharField(widget=forms.PasswordInput, label="Confirm password") first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) gender = forms.ChoiceField(choices=((None, ''), ('F', 'Female'), ('M', 'Male'), ('O', 'Other'))) receive_news = forms.BooleanField( required=False, label='I want to receive news and special offers') agree_toc = forms.BooleanField( required=True, label='I agree with the Terms and Conditions') layout = Layout( 'username', 'email', Row('password', 'password_confirm'), Fieldset('Pesonal details', Row('first_name', 'last_name'), 'gender', 'receive_news', 'agree_toc')) template = Template(""" {% form %} {% part form.username prefix %}<i class="material-icons prefix">account_box</i>{% endpart %} {% part form.email prefix %}<i class="material-icons prefix">email</i>{% endpart %} {% part form.password prefix %}<i class="material-icons prefix">lock_open</i>{% endpart %} {% endform %} """) buttons = Template(""" <button class="waves-effect waves-light btn" type="submit">Submit</button> """) title = "Registration form"
class RegisterAbsenceForm(forms.Form): layout = Layout( Fieldset("", Row("date_start", "date_end"), Row("from_period", "to_period")), Fieldset("", Row("absent", "excused"), Row("excuse_type"), Row("remarks")), ) date_start = forms.DateField(label=_("Start date"), initial=datetime.today) date_end = forms.DateField(label=_("End date"), initial=datetime.today) from_period = forms.ChoiceField(label=_("Start period")) to_period = forms.ChoiceField(label=_("End period")) absent = forms.BooleanField(label=_("Absent"), initial=True, required=False) excused = forms.BooleanField(label=_("Excused"), initial=True, required=False) excuse_type = forms.ModelChoiceField( label=_("Excuse type"), queryset=ExcuseType.objects.all(), widget=Select2Widget, required=False, ) remarks = forms.CharField(label=_("Remarks"), max_length=30, required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) period_choices = TimePeriod.period_choices self.fields["from_period"].choices = period_choices self.fields["to_period"].choices = period_choices self.fields["from_period"].initial = TimePeriod.period_min self.fields["to_period"].initial = TimePeriod.period_max
class AdidasSignupForm(forms.ModelForm): layout = Layout( Row( 'username', 'email', ), Row( 'password1', 'password2', ), Row( 'first_name', 'last_name', ), Row('birth_date'), Row('image', 'phone_number'), ) class Meta: model = get_user_model() fields = ('username', 'email', 'first_name', 'last_name', 'birth_date', 'phone_number', 'image') def signup(self, request, user): user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.birth_date = self.cleaned_data['birth_date'] user.phone_number = self.cleaned_data['phone_number'] user.image = self.cleaned_data['image'] user.save()
class EditProfileFormMedical(forms.ModelForm): email = forms.EmailField(label="Email Address") first_name = forms.CharField(required=True, label='Name') mobile_no = forms.CharField(required=True) emergency_mobile = forms.CharField(required=True, label='Secondary Phone Number') address = forms.CharField(required=True) pin_code = forms.CharField(required=True) other_info = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Any other information you want us to know.'}), required=False) layout = Layout( 'email', Fieldset( 'More Details', Row('first_name'), Row('mobile_no', 'emergency_mobile'), 'address', 'pin_code', 'other_info', )) class Meta: model = User fields = [ 'email', 'first_name', 'mobile_no', 'emergency_mobile', 'address', 'pin_code', 'other_info' ]
class StartView( LayoutMixin, flow.ManagedStartViewActivation, flow_views.StartActivationViewMixin, extra_views.NamedFormsetsMixin, extra_views.UpdateWithInlinesView, ): model = models.OrderProcess model2 = models.OrderItem layout = Layout(Inline('Device Info', ItemInline), ) count = 0 # get_object 가 한번 만 실행되게 만들어주는것 def get_object(self): if self.count == 1: # 두번째 config save 하면서 시작 하는것 print 'start second' StartView.count = 0 return self.process # 첫번째 start 누르면서 시작할거 StartView.count += 1 print 'start first' devices_info[:] = [] print devices_info return self.process
class NewWasherView(CreateView): model = Register form_class = UploadForm def get_success_url(self): return reverse('done') layout = Layout( Row('first_name'), Row('emiil', 'sex'), ) def form_valid(self, form): form.instance.status = False form.instance.working = False first_name = form.instance.first_name emiil = form.instance.emiil dir = os.path.join(settings.BASE_DIR, "templates", "email_washer.html") archivo = open(dir, "r") contenido = archivo.read() contenido = contenido.format(first_name) subject = 'washme' text_content = 'Mensaje...nLinea 2nLinea3' html_content = contenido from_email = '"origen" <*****@*****.**>' to = emiil msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return super(NewWasherView, self).form_valid(form)
class RegistrationForm(forms.Form, UserCreationForm): username = forms.CharField(max_length=30, required=True, label='Login') email = forms.EmailField(label="E-mail", required=True) #senha = forms.CharField(widget=forms.PasswordInput,label='Senha') #confirma_senha = forms.CharField(widget=forms.PasswordInput, label="Confirmar senha") nome = forms.CharField(required=True, label='Nome Completo') cep = forms.IntegerField(max_value=99999999, required=True, label='CEP') #tipo_logradouro = forms.CharField(required=True,label='Tipo') logradouro = forms.CharField(required=True, label='Logradouro') numero = forms.CharField(required=True, label='Número') bairro = forms.CharField(required=True, label='Bairro') cidade = forms.CharField(required=True, label='Cidade') estado = forms.CharField(required=True, label='UF') #last_name = forms.CharField(required=True, label='Último nome') #gender = forms.ChoiceField(choices=((None, ''), ('F', 'Feminino'), ('M', 'Masculino'), ('O', 'Outro')),label='Gênero',required=False) profissional = forms.BooleanField(required=False, label='Sou profissional.') agree_toc = forms.BooleanField( required=True, label='Eu aceito os termos e condições de uso.') layout = Layout( Fieldset('Cadastrar em SOS my PC', 'username', 'email', Row('password1', 'password2')), Fieldset( 'Dados Pessoais', 'nome', Row( Span2('cep'), # Span2('tipo_logradouro'), Span8('logradouro'), Span2('numero')), Row(Span5('bairro'), Span5('cidade'), Span2('estado'))), 'profissional', 'agree_toc')
class RepresentativeForm(forms.ModelForm): class Meta: model = Client fields = ( 'cdalterdata', 'name', 'phone', 'cpf_cnpj', 'email', 'cep', 'logradouro', 'numero', 'bairro', 'cidade', 'estado', ) exclude = ('representative', 'is_representative', 'last_search', 'priority',) layout = Layout( Fieldset("Filial ou Representação", Row(Span3('cdalterdata'), Span9('name'), ), Row(Span4('phone'), Span8('cpf_cnpj')), Row(Span12('email'), ), ), Fieldset('Endereço', Row(Span2('cep'), Span8('logradouro'), Span2('numero')), Row(Span5('bairro'), Span5('cidade'), Span2('estado'))) )
class QuestionForm(forms.ModelForm): # Interessante level = forms.ChoiceField( choices=( ('0', 'Dependencia'), ('1', 'Confianca'), ('2', 'Comprometimento'), ('3', 'Preditiva'),), label='Escolha o nível', widget=forms.RadioSelect) class Meta: model = Question fields = ( 'question', 'level', ) layout = Layout( Fieldset("Inclua uma Pergunta", Row('question', ), Row('level') ) )
class ClientForm(forms.ModelForm): representative = forms.ModelChoiceField(queryset=Client.objects.filter(is_representative=True), required=False, label="Representante (Matriz ou Filial)", ) class Meta: model = Client fields = ( 'cdalterdata', 'name', 'phone', 'cpf_cnpj', 'email', 'cep', 'logradouro', 'numero', 'bairro', 'cidade', 'estado', 'representative', 'last_search', ) exclude = ('is_representative', 'priority',) layout = Layout( Fieldset("Cliente", Row(Span3('cdalterdata'), Span9('name'), ), Row(Span12('representative'), ), Row(Span4('phone'), Span8('cpf_cnpj')), Row(Span9('email'), Span3('last_search'), ), ), Fieldset('Endereço', Row(Span2('cep'), Span8('logradouro'), Span2('numero')), Row(Span5('bairro'), Span5('cidade'), Span2('estado'))) )
class ExRegistrationForm(RegistrationForm): layout = Layout('username', 'email', Row('password1', 'password2')) title = 'Register' template = Template(""" <div class="form register"> <div class="hd"> <img class="l" src="/static/images/registration/lline-v1.png" alt=""> <h3><img src="/static/images/registration/resg-v1.png" alt=""></h3> <img class="r" src="/static/images/registration/rline-v1.png" alt=""> </div> <div class="bd"> <div class="item"> <input id="id_username" maxlength="150" name="username" type="text" autofocus="" value="" placeholder="请输入您的用户名"> </div> <div class="item"> <input id="id_email" name="email" type="email" value="" placeholder="请输入您的邮箱"> </div> <div class="item"> <input class="invalid" id="id_password1" name="password1" type="password" value="" placeholder="请输入您的密码"> </div> <div class="item"> <input class="invalid" id="id_password2" name="password2" type="password" value="" placeholder="请重复你的密码"> </div> <div class="item clearfix"> <p><span class="fl">重置密码</span><span class="fr">已有账号? 点我<a href="/accounts/login/"><em>登录</em></a></span></p> </div> </div> <button class="btn" type="submit"><img src="/static/images/registration/btn-v1.png" alt=""></button> </div> </div> """) buttons = Template(''' {% load i18n %} <button type="submit" name="_submit" class="btn btn-primary btn-lg">{% trans 'Submit' %}</button> ''')
class UsuarioForm(forms.Form): username = forms.CharField( error_messages={'required': 'Campo obligatorio'}, min_length=8, max_length=30, label='Nombre de Usuario', help_text='Al menos 8 caracteres.') first_name = forms.CharField( error_messages={'required': 'Campo obligatorio'}, label='Nombre') last_name = forms.CharField( error_messages={'required': 'Campo obligatorio'}, label='Apellidos') email = forms.EmailField(error_messages={'required': 'Campo obligatorio'}, label='Dirección de Correo Electrónico') try: groups = forms.ChoiceField( choices=[(x.id, x.name) for x in Group.objects.all()], label='Perfil de Acceso', help_text= 'Por favor seleccione el Perfil de Acceso que tendrá este Usuario') except: pass layout = Layout(Fieldset('Agregar Usuario: '), Row('username', 'email'), Row('first_name', 'last_name'), Row('groups')) def clean_email(self): email = self.cleaned_data['email'].lower() username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude( username=username).exists(): raise forms.ValidationError("¡Ya existe un usuario con ese email!") return email
class CreateUserForm(SignUpFormMedical): group_name = forms.ChoiceField(choices=(('doctor', 'Doctor'), ('pharmacy', 'Pharmacy'), ('diagnosis_center', 'Diagnosis Center')), required=True, label='Add this user as') other_info = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'About the institution, add info regarding services it provides etc.' }), required=False, label='About', ) license = forms.FileField(required=False) layout = Layout( 'username', 'email', Row('password1', 'password2'), 'group_name', Fieldset( 'More Details', 'first_name', 'address', 'pin_code', Row('mobile_no', 'emergency_mobile'), 'other_info', )) class Meta: model = User fields = [ 'username', 'email', 'first_name', 'mobile_no', 'emergency_mobile', 'address', 'pin_code', 'other_info' ]
class CustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) self.initial['timezone'] = 'Europe/London' first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') fav_team = forms.ModelChoiceField( queryset=Team.objects.filter(Active=True), empty_label=None, label='Favourite Team') timezone = forms.ChoiceField(choices=timezonelist, label='Timezone') layout = Layout('email', Row('password1', 'password2'), Row('first_name', 'last_name'), Row('fav_team', 'timezone')) class Meta: model = get_user_model() def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.FavouriteTeam = self.cleaned_data['fav_team'] user.Timezone = self.cleaned_data['timezone'] user.save() return user
class EditProfileForm(forms.ModelForm): email = forms.EmailField(label="Email Address") first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) gender = forms.ChoiceField(choices=((None, ''), ('F', 'Female'), ('M', 'Male'), ('O', 'Other')), required=False) birthdate = forms.DateField(required=False) mobile_no = forms.CharField(required=False) emergency_mobile = forms.CharField(required=False) other_info = forms.CharField(widget=forms.TextInput( attrs={ 'placeholder': 'Any other information you want us to know (for example, allergy)' }), required=False) layout = Layout( 'email', Fieldset( 'Personal details', Row('first_name', 'last_name'), Row('gender', 'birthdate'), Row('mobile_no', 'emergency_mobile'), 'other_info', )) class Meta: model = User fields = [ 'email', 'first_name', 'last_name', 'gender', 'birthdate', 'mobile_no', 'emergency_mobile', 'other_info' ]
class TeamDetailView(DetailModelView): """ Retrieve, update or delete a team instance. """ template_name = "team/team_detail.html" model = Team form_class = TeamDetailForm layout = Layout('name', Row('owner', 'join_password'), 'description', ) def get_object_data(self, **kwargs): """List of object fields to display. Choice fields values are expanded to readable choice label. """ #logger.debug(self.object._meta.fields) return super(TeamDetailView, self).get_object_data() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['members_header'] = [('object', 'member') ] context['member_display_links'] = ['name'] context['members'] = TeamMember.objects.filter(team=self.object) return context def has_view_permission(self, request, obj): return request.user.is_authenticated pass
class QuieroSerFiscal2(forms.ModelForm): nombre = forms.CharField() apellido = forms.CharField() telefono = forms.CharField(label='Teléfono', help_text='Preferentemente celular') movilidad = forms.BooleanField( label='¿Tenés Movilidad propia?', required=False, help_text= 'Marcá la casilla si tenés cómo movilizarte el día de la elección') seccion = forms.ModelChoiceField( label='Sección electoral', queryset=Seccion.objects.all(), help_text=mark_safe( f'Sección/departamento donde votás y/o preferís fiscalizar. {LINK}' )) layout = Layout(Row('nombre', 'apellido'), 'telefono', Row('movilidad', 'disponibilidad'), Fieldset('¿Dónde votás?', 'seccion')) class Meta: model = Fiscal fields = [ 'nombre', 'apellido', 'telefono', 'movilidad', 'disponibilidad', 'seccion' ] def clean_telefono(self): valor = self.cleaned_data['telefono'] try: valor = validar_telefono(valor) except (AttributeError, phonenumbers.NumberParseException): raise forms.ValidationError('No es un teléfono válido') return valor
class TeamUpdateView(UpdateModelView): """ Retrieve, update or delete a team instance. """ #template_name = "teams/team_detail_form.html" model = Team form_class = TeamDetailForm layout = Layout(Row('name', 'join_password', 'owner',), 'description', ) def get_object_data(self, **kwargs): """List of object fields to display. Choice fields values are expanded to readable choice label. """ #logger.debug(self.object._meta.fields) return super(TeamUpdateView, self).get_object_data() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context pass
class PatientDeceaseForm(forms.ModelForm): start_date = forms.DateField(widget=forms.DateInput( attrs={'class': 'datepicker'})) end_date = forms.DateField( widget=forms.DateInput(attrs={'class': 'datepicker'}), required=False) patient = forms.ModelChoiceField(queryset=Patient.objects.all(), widget=forms.HiddenInput(), required=False) decease = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'decease-input', 'placeholder': 'Start input decease' })) class Meta: model = PatientDecease fields = ['patient', 'start_date', 'end_date', 'cured'] layout = Layout(Row('decease', 'start_date', 'end_date', 'cured')) def clean_decease(self): if self.prefix: decease_name = self.data[self.prefix + '-decease'] else: decease_name = self.data['decease'] if not Decease.objects.filter(name=decease_name).exists(): raise ValidationError('no such decease') return decease_name
class TeamMemberCreateView(CreateModelView): model = TeamMember form_class = TeamMemberCreateForm template_name = 'team/member_join.html' layout = Layout(Row('team'), Row('password'), Row('rating'), ) def get_form_kwargs(self, **kwargs): '''pass current user to form''' kwargs = super().get_form_kwargs() kwargs['current_user'] = self.request.user return kwargs def has_add_permission(self, request): """Anyone can join a team as long as you know the password. """ return True def get_success_url(self): '''When a team registration is done, go back to the list of teams.''' team_model = Team opts = team_model._meta module = module_registry.get_module(opts.app_label) return reverse(module.get_named_url(opts.model_name, 'list')) pass
def __init__(self, request, *args, **kwargs): self.request = request initial = kwargs.get("initial", {}) # Build layout with or without groups field base_layout = self.layout_base[:] if "groups" in initial: base_layout.remove("groups") self.layout = Layout(*base_layout) super().__init__(*args, **kwargs) if "groups" in initial: self.fields["groups"].required = False # Filter persons and groups by permissions if not self.request.user.has_perm( "alsijil.assign_grouprole"): # Global permission persons = Person.objects if initial.get("groups"): persons = persons.filter(member_of__in=initial["groups"]) if get_site_preferences( )["alsijil__group_owners_can_assign_roles_to_parents"]: persons = persons.filter( Q(member_of__owners=self.request.user.person) | Q(children__member_of__owners=self.request.user.person)) else: persons = persons.filter( member_of__owners=self.request.user.person) self.fields["person"].queryset = persons if "groups" not in initial: groups = Group.objects.for_current_school_term_or_all().filter( owners=self.request.user.person) self.fields["groups"].queryset = groups
class DataControllerForm(forms.ModelForm): full_names = forms.CharField( label='Organization Name', widget=forms.TextInput( attrs={'placeholder': 'e.g. National IT Authority - Uganda'})) address = forms.CharField( label='Physical Address', widget=forms.TextInput( attrs={ 'placeholder': 'e.g. Mackinon Road, Plot 4, Kampala-Uganda' })) email_address = forms.EmailField( label='Email Address', help_text='We will communicate to you via email', widget=forms.EmailInput(attrs={'placeholder': '*****@*****.**'})) phone_number = forms.CharField( min_length=10, max_length=15, error_messages={'required': 'A valid phone number is required'}, help_text='If in another country, specify the country code e.g. +254', widget=forms.TextInput(attrs={'placeholder': '0772123456'})) class Meta: model = DataControllerModel fields = ['full_names', 'address', 'email_address', 'phone_number'] layout = Layout('full_names', 'address', Row('email_address', 'phone_number'))
class ContactForm(forms.Form): name = forms.CharField() email = forms.EmailField() subject = forms.CharField() message = forms.CharField(widget=forms.Textarea) send_copy = forms.BooleanField(required=False, label="Send a copy to my e-mail address") template = Template(""" {% form %} {% part form.name prefix %}<i class="mdi-action-account-box prefix"></i>{% endpart %} {% part form.email prefix %}<i class="mdi-communication-email prefix"></i>{% endpart %} {% part form.subject prefix %}<i class="mdi-action-announcement prefix"></i>{% endpart %} {% part form.message prefix %}<i class="mdi-communication-message prefix"></i>{% endpart %} {% part form.send_copy add_group_class %}right-align{% endpart %} {% endform %} """) layout = Layout(Row('name', 'email'), 'subject', 'message', 'send_copy') buttons = Template(""" <button class="btn btn-primary pull-right" type="submit">Send message</button> """) title = "Contact form"
class BookingsForm(forms.ModelForm): allday = forms.BooleanField(label='Dia inteiro', required=False) title = forms.CharField(label='Titulo do agendamento') start = forms.DateTimeField(label='Inicia em...') end = forms.DateTimeField(label='Termina em...') #created_on = forms.DateTimeField(label='Criado em...') authorized = forms.BooleanField(label='Autorizado', required=False) editable = forms.BooleanField(label='Editavel', required=False) # ABAIXO, CHOICES NO FORMS VAI TER UMALISTAGEM NO TEMPLATE color = forms.ChoiceField(label='Cor', choices=(('blue', 'blue'), ('red', 'red'), ('green', 'green'), ('black', 'black'))) overlap = forms.BooleanField(label='Sobrepor?', required=False) holiday = forms.BooleanField(label='Feriado?', required=False) participants = forms.ModelMultipleChoiceField(label='Participantes', queryset=User.objects.all(), widget=FilteredSelectMultiple("Participantes", is_stacked=False, attrs={'class':'material-ignore', 'multiple':'True'})) class Meta: model = Booking exclude = ['created_on'] fields = '__all__' layout = Layout( Fieldset('Inclua uma agenda', Row('title', ), Row('start','end', 'color'), Row(Span6('holiday'),Span6('authorized'), ), Row(Span6('editable'), Span6('allday')), Row('overlap'), Row('participants') ) )
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["title"] = _("Edit FAQ question") context["layout"] = Layout(Row("question_text"), Row("icon", "show", "section"), Row("answer_text")) return context
def fieldset_layout(adminform, inline_admin_formsets): sets = [] for fieldset in adminform: fields = [] for line in fieldset: line_fields = [] for fieldset_field in line: field = None if getattr(fieldset_field, 'is_readonly', False): field = AdminReadonlyField(fieldset_field) else: field = fieldset_field.field.name line_fields.append(field) if len(line_fields) == 1: fields.append(line_fields[0]) else: fields.append(Row(*line_fields)) if fieldset.name: sets.append(Fieldset(fieldset.name, *fields)) else: sets += fields for inline in inline_admin_formsets: sets.append(TabularInline(inline)) return Layout(*sets)
class ContactForm(forms.Form): name = forms.CharField() email = forms.EmailField() subject = forms.CharField() message = forms.CharField(widget=forms.Textarea) send_copy = forms.BooleanField(required=False, label="Send a copy to my e-mail address") template = Template(""" {% form %} {% part form.name prefix %}<i class="material-icons prefix">account_box</i>{% endpart %} {% part form.email prefix %}<i class="material-icons prefix">email</i>{% endpart %} {% part form.subject prefix %}<i class="material-icons prefix">announcement</i>{% endpart %} {% part form.message prefix %}<i class="material-icons prefix">message</i>{% endpart %} {% attr form.send_copy 'group' class append %}right-align{% endattr %} {% endform %} """) layout = Layout(Row('name', 'email'), 'subject', 'message', 'send_copy') buttons = Template(""" <button class="btn btn-primary pull-right" type="submit">Send message</button> """) title = "Contact form"
class SignupForm(AllauthSignupForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields["password1"].widget.attrs["placeholder"] del self.fields["email"].widget.attrs["placeholder"] del self.fields["password2"].widget.attrs["placeholder"] cpf = forms.CharField( label="CPF", min_length=14, max_length=14, widget=forms.TextInput(attrs={"data-mask": "000.000.000-00"}), validators=[CPFValidator()], ) name = forms.CharField(label="Nome completo", min_length=3, max_length=100, widget=forms.TextInput()) state = forms.ModelChoiceField(label="Estado", queryset=State.objects.all(), empty_label="Escolha um estado") layout = Layout("name", "cpf", "email", "state", "password1", "password2") def clean(self): super().clean() if get_user_model().objects.filter( cpf=self.cleaned_data.get("cpf")).exists(): self.add_error("cpf", "Este CPF já foi registrado.") return self.cleaned_data