class FiltroPorValorForm(forms.Form): CHOICES_EM_CONDOMINIO = ((True, "Apenas em condomínio fechado"), ("", "Indiferente")) CHOICES_MOBILIADO = (("mobiliado", "Mobiliado"), ("nao_mobiliado", "Não Mobiliado"), ("", "Indiferente")) CHOICES_STATUS = (("publicado", "Publicado"), ("arquivado", "Arquivado")) valor_min = CustomInteger() valor_max = CustomInteger() min_quarto = CustomInteger(initial=3) min_vaga = CustomInteger(initial=2) min_banheiro = CustomInteger(initial=1) min_suite = CustomInteger(initial=1) area_min = CustomInteger(initial=180) codigo_referencia = MultipleInteger(label="Código Referência", required=False) bairros = forms.MultipleChoiceField(required=False) em_condominio = forms.ChoiceField(choices=CHOICES_EM_CONDOMINIO, widget=forms.RadioSelect(), initial=CHOICES_EM_CONDOMINIO[-1], label="Condomínio Fechado?", required=False) mobiliado = forms.ChoiceField(choices=CHOICES_MOBILIADO, widget=forms.RadioSelect(), initial=CHOICES_MOBILIADO[-1], label="Mobília", required=False) status = forms.ChoiceField(choices=CHOICES_STATUS, widget=forms.RadioSelect(), initial=CHOICES_STATUS[0], label="Status", required=False) condominio = forms.ChoiceField(widget=forms.Select(), label="Condomínio", required=False) def __init__(self, tipo_imovel=None, tipo_interesse=None, cidade=None, *args, **kwargs): super(FiltroPorValorForm, self).__init__(*args, **kwargs) qs = BairroComImoveis.objects.filter( tipo_imovel=tipo_imovel, cidade__nome=cidade).select_related('cidade', 'bairro' ) if tipo_interesse == 'comprar': qs = qs.filter(contador_venda__gt=0) self.fields["valor_min"].initial = 160000 self.fields["valor_max"].initial = 600000 else: self.fields["valor_min"].initial = 700 self.fields["valor_max"].initial = 2500 qs = qs.filter(contador_locacao__gt=0) bairro_list = [(bairro.bairro.id, bairro) for bairro in qs] bairro_list = sorted(bairro_list, key = lambda tup: tup[1].bairro.descricao) condominio_list = [('', '---------------')] condominio_list += [(condominio.id, condominio.nome) for condominio in Condominio.objects.filter(cidade__nome=cidade).select_related('cidade', )] self.fields['bairros'].widget = BairroComImoveisCheckboxSelectMultiple( attrs={'tipo_interesse': tipo_interesse}) self.fields["condominio"].choices = condominio_list self.fields["condominio"].initial = condominio_list[0] self.fields['bairros'].choices = bairro_list
class CheckboxForm(forms.Form): numbers = forms.MultipleChoiceField( choices=( ('1', '1'), ('2', '2'), ('3', '3'), ), widget=otree.forms.CheckboxSelectMultipleHorizontal)
def _add_subscription_types_field(self, contact=None): """add the subscription_type field dynamically""" subscription_types = list(self.get_queryset()) self.subscription_types_count = len(subscription_types) if self.subscription_types_count > 0: if self.subscription_types_count > 1: help_text = ugettext( 'Check the boxes of the newsletters that you want to receive' ) else: help_text = ugettext( 'Check the box if you want to receive our newsletter') initial = None if contact: initial = ','.join([ str(subscription.subscription_type.id) for subscription in contact.subscription_set.all() if subscription.accept_subscription ]) self.fields['subscription_types'] = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple(), label='', help_text=help_text, required=self.subscription_required and (self.subscription_types_count == 1), initial=initial, choices=[(subscription_type.id, subscription_type.name) for subscription_type in subscription_types]) else: self.fields['subscription_types'] = forms.MultipleChoiceField( widget=forms.HiddenInput(), label='', required=False, choices=[])
class BasicForm(forms.Form): """ TODO:-------------------------- input TextInput OK inputN NumberInput OK inputEmail EmailInput textarea TextInput OK drowpdown Select OK drowpdown SelectMultiple OK checkbox CheckboxInput checkbox2 MultiCheckbox? radiobox RadioSelect date DateInput time TimeInput datetime DateTimeInput """ COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] name = forms.CharField(max_length=32, widget=widgets.TextInput()) year = forms.IntegerField(widget=widgets.NumberInput()) description = forms.CharField(max_length=32, widget=widgets.Textarea(attrs={'rows': '4'})) color = forms.ChoiceField(widget=widgets.Select(), choices=COLORS_CHOICES) colors = forms.MultipleChoiceField(widget=widgets.Select(attrs={'multiple': True}), choices=COLORS_CHOICES) is_boolean = forms.CharField(max_length=32, widget=widgets.CheckboxInput()) option = forms.ChoiceField(widget=widgets.RadioSelect(), choices=COLORS_CHOICES) is_not_boolean = forms.CharField(max_length=32, widget=widgets.CheckboxInput()) option_again = forms.CharField(max_length=32, widget=widgets.CheckboxInput()) def __init__(self, *args, **kwargs): super(BasicForm, self).__init__(*args, **kwargs) self.fields["year"].initial = 2021
class UserRegistrationForm(ModelFormWithCity, SubscriptionTypeFormMixin): """A form for creating a new account on a website""" email = EmailField(required=True, label=_("Email"), widget=forms.TextInput()) password1 = forms.CharField(required=True, widget=forms.PasswordInput(), label=_("Password")) password2 = forms.CharField(required=True, widget=forms.PasswordInput(), label=_("Repeat your password")) entity_type = forms.ChoiceField(required=False, widget=forms.Select()) entity = forms.CharField( required=False, widget=forms.TextInput(attrs={'placeholder': _('Name of the entity')})) groups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label='', required=False) accept_termofuse = forms.BooleanField( label=_('Accept terms of use'), help_text=_("Check for accepting the terms of use")) city = forms.CharField( required=False, label=_('City'), widget=CityAutoComplete(attrs={ 'placeholder': _('Enter a city'), 'size': '80' })) class Meta: model = ContactProfile fields = ('email', 'password1', 'password2', 'entity_type', 'entity', 'gender', 'firstname', 'lastname', 'phone', 'mobile', 'address', 'zip_code', 'city', 'cedex', 'country', 'groups', 'accept_termofuse') def __init__(self, *args, **kwargs): super(UserRegistrationForm, self).__init__(*args, **kwargs) if 'gender' in self.fields: # do not display Mrs and Mr self.fields['gender'].choices = [ (Contact.GENDER_NOT_SET, _('Gender')), (Contact.GENDER_MALE, ugettext('Mr')), (Contact.GENDER_FEMALE, ugettext('Mrs')), ] if 'entity_type' in self.fields: self.fields['entity_type'].choices = [ (0, ugettext('Individual')) ] + [(et.id, et.name) for et in EntityType.objects.filter(subscribe_form=True)] if not has_entity_on_registration_form(): self.fields['entity_type'].inital = 0 self.fields['entity_type'].widget = forms.HiddenInput() self.fields['entity'].widget = forms.HiddenInput() termsofuse_url = get_registration_accept_terms_of_use_link() if 'accept_termofuse' in self.fields and termsofuse_url: self.fields['accept_termofuse'].label = mark_safe( ugettext('Accept <a href="{0}">terms of use</a>').format( termsofuse_url)) self._add_subscription_types_field() def clean_entity(self, ): entity_type = self.cleaned_data.get('entity_type', None) entity = self.cleaned_data['entity'] if entity_type: if not entity: raise ValidationError( _("{0}: Please enter a name".format(entity_type))) return entity def clean_entity_type(self): try: entity_type_id = int(self.cleaned_data['entity_type'] or 0) except ValueError: raise ValidationError(ugettext('Invalid entity type')) if entity_type_id: try: return EntityType.objects.get(id=entity_type_id) except EntityType.DoesNotExist: raise ValidationError(ugettext('Unknown entity type')) return None def clean(self, *args, **kwargs): password1 = self.cleaned_data.get('password1', "") password2 = self.cleaned_data.get('password2', "") if password1 and (password1 != password2): raise forms.ValidationError(ugettext('Passwords are not the same')) return super(UserRegistrationForm, self).clean(*args, **kwargs) def save(self, commit=True): if get_registration_version() >= "2.0.0": # Django registration 2.0 # The registration form should return a user email = self.cleaned_data["email"] username = email[:30] user = User.objects.create(username=username, email=email, is_active=False) password = self.cleaned_data.get('password1', "") user.set_password(password) return user else: # Django registration 1.0 return super(UserRegistrationForm, self).save(commit)
class MultiForm(forms.Form): multi = forms.MultipleChoiceField(choices=some_choices)
class SubscribeForm(ModelFormWithCity, SubscriptionTypeFormMixin): """Subscribe to emailing""" city = forms.CharField( required=False, label=_('City'), widget=CityAutoComplete(attrs={ 'placeholder': _('Enter a city'), 'size': '80' })) entity_type = forms.ChoiceField(required=False, widget=forms.Select()) entity = forms.CharField( required=False, widget=forms.TextInput(attrs={'placeholder': _('Name of the entity')})) groups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label='', required=False) action_types = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple(), label='', required=False) message = forms.CharField(required=False, widget=forms.Textarea(attrs={ 'placeholder': _('Message'), 'cols': '90' })) captcha = get_captcha_field() favorite_language = forms.CharField(required=False, widget=forms.HiddenInput()) class Meta: model = Contact fields = ('gender', 'firstname', 'lastname', 'phone', 'mobile', 'email', 'address', 'address2', 'address3', 'zip_code') widgets = { 'lastname': forms.TextInput(attrs={ 'placeholder': _('Lastname'), 'required': 'required' }), 'firstname': forms.TextInput(attrs={'placeholder': _('Firstname')}), 'phone': forms.TextInput(attrs={'placeholder': _('Phone')}), 'email': forms.TextInput(attrs={ 'placeholder': _('Email'), 'required': 'required' }), 'zip_code': forms.TextInput(attrs={'placeholder': _('zip code')}), } def __init__(self, *args, **kwargs): super(SubscribeForm, self).__init__(*args, **kwargs) self.fields['email'].required = True # Do not display (Mrs and M) gender on subscribe form self.fields['gender'].choices = [ (models.Contact.GENDER_NOT_SET, _('')), (models.Contact.GENDER_MALE, ugettext('Mr')), (models.Contact.GENDER_FEMALE, ugettext('Mrs')), ] entity_types_choices = [] if crm_settings.ALLOW_SINGLE_CONTACT: entity_types_choices.append((0, _('Individual'))) else: entity_types_choices.append((0, '')) entity_types_choices.extend([ (et.id, et.name) for et in EntityType.objects.filter(subscribe_form=True) ]) self.fields['entity_type'].choices = entity_types_choices self.fields['groups'].choices = [ (group.id, group.name) for group in Group.objects.filter(subscribe_form=True) ] self.fields['action_types'].choices = [ (action_type.id, action_type.name) for action_type in ActionType.objects.filter(subscribe_form=True) ] self._add_subscription_types_field() if crm_settings.has_language_choices(): self.fields['favorite_language'].initial = get_language() def clean_entity_type(self): """validation""" try: entity_type = int(self.cleaned_data['entity_type']) if entity_type: return EntityType.objects.get(id=entity_type) return None except (ValueError, EntityType.DoesNotExist): raise ValidationError(ugettext("Invalid entity type")) def get_entity(self): """get entity from form""" entity_type = self.cleaned_data.get('entity_type', None) entity = self.cleaned_data['entity'] if entity_type: if entity: return Entity.objects.create(name=entity, type=entity_type) else: if crm_settings.ALLOW_SINGLE_CONTACT: return Entity.objects.create(name=entity, type=None, is_single_contact=True) else: et_id = getattr(settings, 'BALAFON_INDIVIDUAL_ENTITY_ID', 1) entity_type = EntityType.objects.get(id=et_id) entity_name = "{0} {1}".format(self.cleaned_data['lastname'], self.cleaned_data['firstname']) return Entity.objects.create(name=entity_name, type=entity_type) def clean_entity(self): """validation""" entity_type = self.cleaned_data.get('entity_type', None) entity = self._dehtmled_field("entity") if entity_type: if not entity: raise ValidationError("{0}: {1}".format( entity_type.name, ugettext("Please enter a name"))) else: data = [self.cleaned_data[x] for x in ('lastname', 'firstname')] entity = ' '.join([x for x in data if x]).strip().upper() return entity def _dehtmled_field(self, fieldname, **kwargs): """html to text for a field content""" value = self.cleaned_data[fieldname] return dehtml(value, **kwargs) def clean_lastname(self): """validate lastname""" return self._dehtmled_field("lastname") def clean_firstname(self): """validate firstname""" return self._dehtmled_field("firstname") def clean_phone(self): """validate phone""" return self._dehtmled_field("phone") def clean_mobile(self): """validate mobile phone""" return self._dehtmled_field("mobile") def clean_address(self): """validate address""" return self._dehtmled_field("address") def clean_address2(self): """valiadate address line 2""" return self._dehtmled_field("address2") def clean_address3(self): """validate address line 3""" return self._dehtmled_field("address3") def clean_message(self): """validate message""" message = self._dehtmled_field("message", allow_spaces=True) if len(message) > 10000: raise ValidationError(ugettext("Your message is too long")) return message def clean_groups(self): """validate groups""" try: groups = [ Group.objects.get(id=group_id) for group_id in self.cleaned_data['groups'] ] except Group.DoesNotExist: raise ValidationError(ugettext("Invalid group")) return groups def clean_action_types(self): """validate action types""" try: action_types = [ ActionType.objects.get(id=at_id) for at_id in self.cleaned_data['action_types'] ] except ActionType.DoesNotExist: raise ValidationError(ugettext("Invalid action type")) return action_types def save(self, request=None): """save""" contact = super(SubscribeForm, self).save(commit=False) contact.entity = self.get_entity() contact.city = self.cleaned_data['city'] contact.favorite_language = self.cleaned_data.get( 'favorite_language', '') contact.save() # delete unknown contacts for the current entity contact.entity.contact_set.filter( lastname='', firstname='').exclude(id=contact.id).delete() # force also the city on the entity contact.entity.city = contact.city groups = self.cleaned_data['groups'] for group in groups: contact.entity.group_set.add(group) contact.entity.save() subscriptions = self._save_subscription_types(contact) message = self.cleaned_data["message"] if message: action_type = ActionType.objects.get_or_create( name=ugettext("Message"))[0] action = Action.objects.create( subject=ugettext("Message from web site"), type=action_type, planned_date=datetime.now(), detail=message, display_on_board=True) action.contacts.add(contact) action.save() if subscriptions: create_subscription_action(contact, subscriptions) action_types = self.cleaned_data['action_types'] actions = [] for action_type in action_types: action = Action.objects.create(subject=ugettext("Contact"), type=action_type, planned_date=datetime.now(), display_on_board=True) action.contacts.add(contact) action.save() actions.append(action) # send an email send_notification_email(request, contact, actions, message) return contact