Beispiel #1
0
    def post_init(self, all_classes=False):
        """init"""
        try:
            instance_fragment_type = self.instance.type
        except FragmentType.DoesNotExist:
            instance_fragment_type = None

        if instance_fragment_type or all_classes:
            if instance_fragment_type:
                css_classes = instance_fragment_type.allowed_css_classes.split(
                    ',')
            else:
                css_classes = []
                for fragment_type in FragmentType.objects.all():
                    fragment_classes = fragment_type.allowed_css_classes.split(
                        ',')
                    for css_class in fragment_classes:
                        if css_class not in css_classes:
                            css_classes.append(css_class)
            if css_classes:
                choices = [('', '')] + [(x, x) for x in css_classes]
                self.fields['css_class'].widget = floppyforms.SelectMultiple(
                    choices=choices,
                    attrs={
                        "class": "chosen-select",
                        "data-placeholder": _("Select CSS classes to apply")
                    })
            else:
                self.fields['css_class'].widget = floppyforms.HiddenInput()
        else:
            self.fields['css_class'].widget = floppyforms.HiddenInput()
Beispiel #2
0
    def add_fields(self, form, index):
        super(BaseBackendInlineFormSet, self).add_fields(form, index)

        if self.order_field and self.order_field in form.fields:
            form.fields[self.order_field].widget = forms.HiddenInput()
        if self.can_delete:
            form.fields['DELETE'].widget = forms.HiddenInput()
Beispiel #3
0
 class Meta:
     model = Poll
     exclude = ['status', 'status_changed']
     widgets = {
         'poll_type': forms.HiddenInput(),
         'create_user': forms.HiddenInput()
     }
Beispiel #4
0
    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()
Beispiel #5
0
 class Meta:
     model = PurchaseAccept
     fields = '__all__'
     widgets = {
         'poll': forms.HiddenInput(),
         'create_user': forms.HiddenInput()
     }
Beispiel #6
0
    def __init__(self, *args, **kwargs):
        super(UpdateEmailingForm, self).__init__(*args, **kwargs)

        subscription_choices = [
            (subs_type.id, subs_type.name)
            for subs_type in SubscriptionType.objects.all()
        ]
        self.fields["subscription_type"].widget = forms.Select(
            choices=subscription_choices)

        newsletter_choices = [(newsletter.id, newsletter.subject)
                              for newsletter in Newsletter.objects.all()]
        self.fields["newsletter"].widget = forms.Select(
            choices=newsletter_choices, attrs={'class': 'form-control'})

        if not getattr(settings, 'BALAFON_EMAILING_SENDER_CHOICES', None):
            self.fields["from_email"].widget = forms.HiddenInput()
        else:
            self.fields["from_email"].widget = forms.Select(
                choices=settings.BALAFON_EMAILING_SENDER_CHOICES)

        if not getattr(settings, 'LANGUAGES',
                       None) or len(settings.LANGUAGES) < 2:
            self.fields["lang"].widget = forms.HiddenInput()
        else:
            language_choices = crm_settings.get_language_choices(
                _("Favorite language of the contact"))
            self.fields["lang"].widget = forms.Select(
                choices=language_choices, attrs={'class': 'form-control'})
Beispiel #7
0
 class Meta:
     model = Item
     fields = '__all__'
     error_messages = {
         NON_FIELD_ERRORS: {
             'unique_together': "Jogo já indicado por um associado.",
         }
     }
     widgets = {
         'poll': forms.HiddenInput(),
         'create_user': forms.HiddenInput()
     }
Beispiel #8
0
 def __init__(self, *args, **kwargs):
     self.instance = kwargs.get('instance')
     super(EditGroupForm, self).__init__(*args, **kwargs)
     self.fields['entities'] = forms.CharField(
         widget=forms.HiddenInput(),
         initial=[elt.id for elt in self.instance.entities.all()]
         if self.instance.id else [],
         required=False,
     )
     self.fields['contacts'] = forms.CharField(
         widget=forms.HiddenInput(),
         initial=[elt.id for elt in self.instance.contacts.all()]
         if self.instance.id else [],
         required=False)
Beispiel #9
0
class ThreadForm(MessageForm):
    """ Formulaire de fil de discussion """
    # Constantes
    SUBJECT_LENGTH_MIN = 1
    # Champs supplémentaires
    subject = forms.CharField(max_length=48,
                              required=False,
                              widget=forms.TextInput())
    recipient = forms.IntegerField(required=True, widget=forms.HiddenInput())

    # Validation
    def clean_subject(self):
        """ Valider et renvoyer les données du champ sujet """
        subject = self.data['subject']
        if len(subject) < ThreadForm.SUBJECT_LENGTH_MIN:
            raise forms.ValidationError(
                _("Your subject must be at least {} characters long.").format(
                    ThreadForm.SUBJECT_LENGTH_MIN))
        return subject

    def clean_recipient(self):
        """ Valider et renvoyer les données du champ destinataire """
        recipient = int(self.data['recipient'])
        if get_user_model().objects.get_or_none(id=recipient) is None:
            raise forms.ValidationError(_("The recipient does not exist."))
        return get_user_model().objects.get(id=recipient)
Beispiel #10
0
 class Meta:
     """form from model"""
     model = models.Action
     fields = ['done']
     widgets = {
         'done': forms.HiddenInput(),
     }
Beispiel #11
0
    def __init__(self, *args, **kwargs):
        self.subscription_type = kwargs.pop('subscription_type', None)
        super(EmailSubscribeForm, self).__init__(*args, **kwargs)

        self.fields['favorite_language'].widget = forms.HiddenInput()
        if crm_settings.has_language_choices():
            self.fields['favorite_language'].initial = get_language()
Beispiel #12
0
    def __init__(self, *args, **kwargs):
        super(MinimalUserRegistrationForm, self).__init__(*args, **kwargs)
        for hidden_field in ('entity', 'entity_type', 'zip_code', 'city',
                             'country', 'groups_ids'):
            self.fields[hidden_field].widget = forms.HiddenInput()

        for required_field in ('firstname', 'lastname'):
            self.fields[required_field].required = True
Beispiel #13
0
class SearchActionForm(BsForm, SearchActionBaseMixin):
    """Base class for any views which needs to get extra information for handling results"""
    contacts = forms.CharField(widget=forms.HiddenInput())
    
    def __init__(self, *args, **kwargs):
        initial_contacts = self._pre_init(*args, **kwargs)
        super(SearchActionForm, self).__init__(*args, **kwargs)
        self._post_init(initial_contacts)
Beispiel #14
0
    def __init__(self, *args, **kwargs):
        super(NewNewsletterForm, self).__init__(*args, **kwargs)

        self.source_content = ""

        self.allow_url_sources = getattr(settings,
                                         'BALAFON_NEWSLETTER_SOURCES', ())
        if not self.allow_url_sources:
            self.fields['source_url'].widget = forms.HiddenInput()
Beispiel #15
0
class PdfTemplateForm(SearchActionForm):
    """Form for Pdf generation"""
    search_dict = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super(PdfTemplateForm, self).__init__(*args, **kwargs)

        if getattr(settings, 'BALAFON_PDF_TEMPLATES', None):
            choices = settings.BALAFON_PDF_TEMPLATES
        else:
            choices = (
                ('pdf/labels_24.html', _('etiquettes 24')),
                ('pdf/labels_21.html', _('etiquettes 21')),
                ('pdf/agipa_21.html', _('Agipa 21')),
                ('pdf/labels_16.html', _('etiquettes 16')),
                ('pdf/address_strip.html', _('bande adresse')),
            )

        self.fields['template'] = forms.ChoiceField(
            choices=choices,
            required=True,
            label=_('template'),
            help_text=_('Select the type of document to generate'))
        self.fields['template'].widget.attrs.update({'class': 'form-control'})

        extra_fields = getattr(settings, 'BALAFON_PDF_FORM_EXTRA_FIELDS', None)
        if extra_fields:
            for field_name, field_label, initial_value in extra_fields:
                self.fields[field_name] = forms.CharField(
                    label=field_label, initial=initial_value)
                self.fields[field_name].widget.attrs.update(
                    {'class': 'form-control'})

    def patch_context(self, context):
        """
        add to data from external function in context
        It can be used for example for adding blank labels in labels generation
        """
        template = self.cleaned_data['template']
        extra_data = self._get_extra_data()
        context.update(extra_data)
        hooks = getattr(settings, 'BALAFON_PDF_FORM_CONTEXT_HOOKS', {})
        if hooks and template in hooks:
            context = hooks[template](template, context)
        return context

    def _get_extra_data(self):
        """
        This extra_data comes from additional fields defined in BALAFON_PDF_FORM_EXTRA_FIELDS settings
        These values are passed to the template
        """
        extra_data = dict(self.cleaned_data)
        for field in ('template', 'contacts', 'search_dict'):
            extra_data.pop(field)
        return extra_data
Beispiel #16
0
class ContatarAnuncianteForm(forms.Form):
    imovel_ref = forms.CharField(widget=forms.HiddenInput())
    email = forms.EmailField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu email'}),
      label='E-mail')
    telefone = forms.CharField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu telefone'}))
    nome = forms.CharField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu nome'}),
      label='Nome')
    sobrenome = forms.CharField(
      widget=forms.TextInput(attrs={'placeholder': 'Digite seu sobrenome'}),
      label='Sobrenome')
    mensagem = forms.CharField(
      widget=forms.Textarea(attrs={'rows': 3,
                                   'cols': 45,
                                   'placeholder': 'Precisa mais informações do imóvel ou gostaria de agendar uma visita?'}, 
                                   ),
                            label='Mensagem',
                            required=False)

    def __init__(self, *args, **kwargs):
        super(ContatarAnuncianteForm, self).__init__(*args, **kwargs)
        

    def clean_telefone(self):
        telefone = self.cleaned_data['telefone']
        # not re.match(r'^(\(\d{2}\)) ?(\d{5}-\d{4}|\d{9}|\d{4}-\d{4}|\d{8})$',
        # telefone)
        if len(telefone) < 9:
            raise forms.ValidationError("Digite um telefone válido.")
        return telefone

    def envia_email(self):
        sender = MagicEmail("{0}".format(settings.DEFAULT_FROM_EMAIL))
        current_site = Site.objects.get_current()
        subject = "[SJC Vale Imóveis] Novo Contato: Ref: {0} ".format(
          self.cleaned_data['imovel_ref'])
        data = {'domain': current_site.domain,
                'body': subject,
                'imovel_ref': self.cleaned_data['imovel_ref'],
                'email': self.cleaned_data['email'],
                'telefone': self.cleaned_data['telefone'],
                'nome': self.cleaned_data['nome'],
                'sobrenome': self.cleaned_data['sobrenome'],
                'mensagem': self.cleaned_data['mensagem'],
                'url': reverse('buscador.lista.imovel_referencia',
                               args=[self.cleaned_data['imovel_ref'], ]), }

        email_contato = preferences.ImobiliariaPreferences.email_contato
        sender.using_template(
            "contato_cliente_imovel", data) \
            .with_subject(subject) \
            .reply_to(self.cleaned_data['email']) \
            .send_to([email_contato, ])
Beispiel #17
0
 def __init__(self, *args, **kwargs):
     super(StoreManagementActionTypeAdminForm,
           self).__init__(*args, **kwargs)
     if self.instance and self.instance.id and self.instance.action_type:
         self.initial_show_amount_as_pre_tax = self.instance.show_amount_as_pre_tax
         self.fields[
             'readonly_status'].queryset = self.instance.action_type.allowed_status
     else:
         self.fields[
             'readonly_status'].queryset = ActionStatus.objects.none()
         self.fields['readonly_status'].widget = forms.HiddenInput()
Beispiel #18
0
 def __init__(self, *args, **kwargs):
     """
     Reduce available options for non staff members, as they are not easy
     to understand.
     """
     super().__init__(*args, **kwargs)
     if not kwargs['instance'].user.is_staff:
         self.fields['subscription'].choices = [
             settings.NOTIFICATIONS_EMAIL_SUBSCRIPTIONS[0],
             settings.NOTIFICATIONS_EMAIL_SUBSCRIPTIONS[2]
         ]
         self.fields['wanted_actions'].widget = forms.HiddenInput()
Beispiel #19
0
    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial')
        initial_contacts = ''
        if initial and 'contacts' in initial:
            initial_contacts = ';'.join(
                ['{0}'.format(contact.id) for contact in initial['contacts']])
            initial.pop('contacts')
        super(NewEmailingForm, self).__init__(*args, **kwargs)
        if initial_contacts:
            self.fields['contacts'].initial = initial_contacts

        newsletter_choices = [(0, ugettext('-- New --'))] + [
            (newsletter.id, newsletter.subject)
            for newsletter in Newsletter.objects.all().order_by('-id')
        ]
        self.fields["newsletter"].widget = forms.Select(
            choices=newsletter_choices, attrs={'class': 'form-control'})

        subscription_choices = [
            (subscription.id, subscription.name)
            for subscription in SubscriptionType.objects.all()
        ]
        self.fields["subscription_type"].widget = forms.Select(
            choices=subscription_choices, attrs={'class': 'form-control'})

        if not getattr(settings, 'LANGUAGES',
                       None) or len(settings.LANGUAGES) < 2:
            self.fields["lang"].widget = forms.HiddenInput()
        else:
            language_choices = crm_settings.get_language_choices(
                _("Favorite language of the contact"))
            self.fields["lang"].widget = forms.Select(
                choices=language_choices, attrs={'class': 'form-control'})

        if getattr(settings, 'BALAFON_EMAILING_SENDER_CHOICES', None):
            self.fields['from_email'].widget = forms.Select(
                choices=settings.BALAFON_EMAILING_SENDER_CHOICES,
                attrs={'class': 'form-control'})
        else:
            self.fields['from_email'].widget = forms.HiddenInput()
Beispiel #20
0
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        if instance:
            prefix = " ".join([
                instance.street_number,
                instance.street_type.name if instance.street_type else '',
            ]).strip()
            instance.address = instance.address.replace(prefix, '', 1).strip()

            billing_prefix = " ".join([
                instance.billing_street_number,
                instance.billing_street_type.name
                if instance.billing_street_type else '',
            ]).strip()
            instance.billing_address = instance.billing_address.replace(
                billing_prefix, '', 1).strip()

        super(ModelFormWithAddress, self).__init__(*args, **kwargs)

        if not models.StreetType.objects.count():
            self.fields['street_number'].widget = forms.HiddenInput()
            self.fields['street_type'].widget = forms.HiddenInput()
            self.fields['billing_street_number'].widget = forms.HiddenInput()
            self.fields['billing_street_type'].widget = forms.HiddenInput()
Beispiel #21
0
 class Meta:
     model = TurtleObservation
     exclude = (
         'uid',
         'email_uid',
     )
     widgets = {
         'point': GoogleLeafletWidget(),
         'point_accuracy': forms.HiddenInput(),
     }
     labels = {
         'observer': _("Your Name"),
         'email': _("Your Email"),
         'phone': _("Your Phone"),
     }
Beispiel #22
0
class SelectContactOrEntityForm(forms.Form):
    """Select a contact or entity"""
    object_id = forms.IntegerField(widget=forms.HiddenInput(), required=True)
    object_type = forms.CharField(widget=forms.HiddenInput(), required=True)
    name = forms.CharField(required=True, label=_('Name'))

    def clean_name(self):
        """validation"""
        object_id = self.cleaned_data.get('object_id', '')
        object_type = self.cleaned_data.get('object_type', '')
        object_class = {
            'contact': models.Contact,
            'entity': models.Entity,
        }.get(object_type, None)

        if not object_class:
            raise ValidationError(
                ugettext("Invalid type '{0}'").format(object_type))

        try:
            object_id = int(object_id)
            return object_class.objects.get(id=object_id)
        except (ValueError, object_class.DoesNotExist):
            raise ValidationError(ugettext("Does'nt exist"))
Beispiel #23
0
class SearchNameForm(forms.Form):
    """Save search form"""
    search_id = forms.IntegerField(required=False, widget=forms.HiddenInput())
    name = forms.CharField(required=True, label=_("Name"))
    search_fields = forms.CharField(required=True, widget=forms.HiddenInput())
    
    def clean_name(self):
        """validate name"""
        search_id = self.cleaned_data["search_id"]
        
        name = self.cleaned_data["name"]
        if not name:
            raise ValidationError(_("This field is required"))
        
        queryset = models.Search.objects.filter(name=name)
        if search_id:
            queryset = queryset.exclude(id=search_id)
        if queryset.count() > 0:
            raise ValidationError(_("This name is already used"))
        
        if search_id:
            search = models.Search.objects.get(id=search_id)
            if search.name != name:
                search.name = name
                search.save()
        else:
            search = models.Search(name=name)        
        return search
    
    def clean_search_fields(self):
        """validate search fields"""
        search_fields = self.cleaned_data["search_fields"]
        data = json.loads(search_fields)
        for key in ('csrfmiddlewaretoken', 'excluded', 'name', 'field_choice'):
            data.pop(key, None)
        return data
Beispiel #24
0
    def __init__(self, action_type, *args, **kwargs):
        super(CloneActionForm, self).__init__(*args, **kwargs)

        choices = [(action_type.id, action_type.name) for action_type in
                   action_type.next_action_types.all().order_by('order_index')]
        self.fields['action_type'].choices = choices
        # If only 1 choice = change it to a confirmation
        if len(choices) == 1:
            self.fields['action_type'].initial = choices[0][0]
            self.fields['action_type'].widget = forms.HiddenInput()
            self.single_choice = True
            self.action_type_name = choices[0][1]
        else:
            self.single_choice = False
            self.action_type_name = ''
Beispiel #25
0
 def __init__(self, contact, *args, **kwargs):
     super(SameAsForm, self).__init__(*args, **kwargs)
     potential_contacts = get_suggested_same_as_contacts(
         contact_id=contact.id,
         lastname=contact.lastname,
         firstname=contact.firstname,
         email=contact.email)
     if contact.same_as:
         # Do not propose again current SameAs
         potential_contacts = potential_contacts.exclude(
             same_as=contact.same_as)
     self._same_as = [(same_as_contact.id, "{0}".format(same_as_contact))
                      for same_as_contact in potential_contacts]
     if len(self._same_as):
         self.fields["contact"].widget = forms.Select(choices=self._same_as)
     else:
         self.fields["contact"].widget = forms.HiddenInput()
Beispiel #26
0
 class Meta():
     model = Message
     fields = (
         'title',
         'message',
         'messageType',
         'category',
         'address',
         'location',
         'is_anonymous',
         'allow_feedback',
         'is_virtual',
     )
     widgets = {
         'messageType': forms.HiddenInput(),
         'category': forms.CheckboxSelectMultiple(),
         'location': LeafletWidget(),
     }
Beispiel #27
0
class ActionForContactsForm(forms.ModelForm):
    """Create action for contacts"""
    date = forms.DateField(label=_("planned date"),
                           required=False,
                           widget=forms.TextInput())
    time = forms.TimeField(label=_("planned time"), required=False)
    contacts = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        """create form from model"""
        model = Action
        fields = ('date', 'time', 'type', 'subject', 'in_charge', 'detail',
                  'planned_date', 'contacts', 'opportunity')

    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial')
        initial_contacts = ''
        if initial and 'contacts' in initial:
            initial_contacts = ';'.join(
                ['{0}'.format(c.id) for c in initial['contacts']])
            initial.pop('contacts')
        super(ActionForContactsForm, self).__init__(*args, **kwargs)
        if initial_contacts:
            self.fields['contacts'].initial = initial_contacts
        self.fields['opportunity'].widget = OpportunityAutoComplete(
            attrs={
                'placeholder': _('Enter the name of an opportunity'),
                'size': '80',
                'class': 'colorbox'
            })

    def get_contacts(self):
        """return contacts"""
        contact_ids = self.cleaned_data["contacts"].split(";")
        return Contact.objects.filter(id__in=contact_ids)

    def clean_planned_date(self):
        """validate planned date"""
        the_date = self.cleaned_data["date"]
        the_time = self.cleaned_data.get("time", None)
        if the_date:
            return datetime.combine(the_date, the_time or datetime.min.time())
        return None
Beispiel #28
0
class GroupForContactsForm(forms.Form):
    """Add contacts to group"""
    contacts = forms.CharField(widget=forms.HiddenInput())
    groups = HidableModelMultipleChoiceField(queryset=Group.objects.all())
    on_contact = forms.BooleanField(
        label=_("Group on contact"),
        required=False,
        initial=True,
        help_text=_("Define if the group is added on the contact itself or on his entity")
    )
    
    class Media:
        """media files"""
        css = {
            'all': ('chosen/chosen.css',)
        }
        js = (
            'chosen/chosen.jquery.js',
        )
        
    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial')
        initial_contacts = ''
        if initial and 'contacts' in initial:
            initial_contacts = ';'.join(['{0}'.format(contact.id) for contact in initial['contacts']])
            initial.pop('contacts')
        super(GroupForContactsForm, self).__init__(*args, **kwargs)
        if initial_contacts:
            self.fields['contacts'].initial = initial_contacts
    
        self.fields['groups'].widget.attrs = {
            'class': 'chzn-select',
            'data-placeholder': _('Select groups'),
            'style': "width:350px;"
        }
        self.fields['groups'].help_text = ''

    def get_contacts(self):
        """get contacts"""
        contact_ids = self.cleaned_data["contacts"].split(";")
        return Contact.objects.filter(id__in=contact_ids)
Beispiel #29
0
class SortableNewsletterForm(NewsletterForm):
    """Example of newsletter form"""
    # cleaned_data = None

    sortable = forms.CharField(required=False, widget=forms.HiddenInput())

    class Media(NewsletterForm.Media):
        js = NewsletterForm.Media.js + ('js/jquery.sortElements.js', )

    def save(self, *args, **kwargs):
        """override save"""
        ret = super(SortableNewsletterForm, self).save(*args, **kwargs)

        order = self.cleaned_data['sortable']
        if order:
            order = [int(x) for x in order.split(';')]
            for art_id in order:
                section = ArticleCategory.objects.get(id=art_id)
                section.ordering = order.index(art_id) + 1
                section.save()

        return ret
Beispiel #30
0
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        super(UpdateActionStatusForm, self).__init__(*args, **kwargs)

        if instance and instance.id and instance.type and instance.type.allowed_status.count():
            # let javascript disable the blank value if default_status
            allowed_status = instance.type.allowed_status.all()
            if instance.frozen:
                allowed_status = allowed_status.filter(allowed_on_frozen=True)
            self.fields['status'].choices = [
                (status.id, status.name) for status in allowed_status
            ]

        if instance and instance.id and instance.type and instance.type.allowed_status2.count():
            # let javascript disable the blank value if default_status2
            allowed_status2 = instance.type.allowed_status2.all()
            if instance.frozen:
                allowed_status2 = allowed_status2.filter(allowed_on_frozen=True)
            self.fields['status2'].choices = [
                (status.id, status.name) for status in allowed_status2
            ]
        else:
            self.fields['status2'].widget = forms.HiddenInput()