Esempio n. 1
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'})
Esempio n. 2
0
 def render(self, name, value=None, attrs=None, choices=()):
     pb, pb_desc = None, None
     juris_widget = None
     jurisdictions = Jurisdiction.objects.get_visible()
     if value is not None:
         try:
             pb = PublicBody.objects.get(pk=int(value))
             pb_desc = pb.get_label()
         except (ValueError, PublicBody.DoesNotExist):
             pass
     if len(jurisdictions) > 1:
         attrs = {
             "id": "id_juris_%s" % name,
             "class": "search-public_bodies-jurisdiction"
         }
         choices = [(j.name, j.name) for j in jurisdictions]
         juris_widget = forms.Select(choices=choices, attrs=attrs)
         if pb is None:
             juris_widget = juris_widget.render('jurisdiction',
                                                self.initial_jurisdiction)
         else:
             juris_widget = juris_widget.render('jurisdiction',
                                                pb.jurisdiction.name)
         juris_widget = mark_safe(juris_widget)
     return render_to_string(
         'publicbody/_chooser.html', {
             'name': name,
             'value': value,
             'value_label': pb_desc,
             'search': self.initial_search,
             'juris_widget': juris_widget,
             'STATIC_URL': settings.STATIC_URL
         })
Esempio n. 3
0
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
Esempio n. 4
0
 def __init__(self, *args, **kwargs):
     super(BetterBsModelForm, self).__init__(*args, **kwargs)
     self._bs_patch_field_class()
     for field in self.fields.values():
         if field.widget.__class__.__name__ == forms.Select(
         ).__class__.__name__:
             css_class = field.widget.attrs.get("class", "")
             if "chosen-select" not in css_class:
                 field.widget.attrs["class"] = css_class + " chosen-select"
Esempio n. 5
0
 def __init__(self, foirequest, *args, **kwargs):
     super(FoiRequestStatusForm, self).__init__(*args, **kwargs)
     self.foirequest = foirequest
     self.fields['refusal_reason'] = forms.ChoiceField(
         label=_("Refusal Reason"),
         choices=[('', _('No or other reason given'))] +
         (foirequest.law.get_refusal_reason_choices()),
         required=False,
         widget=forms.Select(attrs={'class': 'form-control'}),
         help_text=
         _('When you are (partially) denied access to information, the Public Body should always state the reason.'
           ))
Esempio n. 6
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()
Esempio n. 7
0
 def __init__(self, *args, **kwargs):
     choices = kwargs.pop('choices', None)
     super(SelectContactForm, self).__init__(*args, **kwargs)
     if choices:
         widget = forms.Select(choices=[(x.id, x.fullname)
                                        for x in choices])
         self.fields["contact"] = forms.IntegerField(label=_("Contact"),
                                                     widget=widget)
     else:
         widget = ContactAutoComplete(
             attrs={
                 'placeholder': _('Enter the name of a contact'),
                 'size': '50',
                 'class': 'colorbox'
             })
         self.fields["contact"] = forms.CharField(label=_("Contact"),
                                                  widget=widget)
Esempio n. 8
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()
Esempio n. 9
0
    def __init__(self, instance, *args, **kwargs):
        super(CustomFieldForm, self).__init__(*args, **kwargs)
        self._instance = instance
        model_type = self._get_model_type()
        custom_fields = models.CustomField.objects.filter(model=model_type)
        for field in custom_fields:
            self.fields[field.name] = forms.CharField(required=False, label=field.label or field.name)
            if field.choices.count():
                choices = [('', '')] + [(choice.value, choice.label) for choice in field.choices.all()]
                self.fields[field.name].widget = forms.Select(choices=choices)
            self.fields[field.name].widget.attrs = {'class': 'form-control'}
            if field.widget:
                self.fields[field.name].widget.attrs['class'] += ' ' + field.widget

            # No Post
            if len(args) == 0:
                self.fields[field.name].initial = getattr(instance, 'custom_field_' + field.name, '')
Esempio n. 10
0
    def __init__(self, contact1, *args, **kwargs):
        super(AddRelationshipForm, self).__init__(*args, **kwargs)

        self.reversed_relation = False
        self.contact1 = contact1

        relationship_types = []
        for relationship_type in models.RelationshipType.objects.all():
            relationship_types.append(
                (relationship_type.id, relationship_type.name))
            if relationship_type.reverse:
                relationship_types.append(
                    (-relationship_type.id, relationship_type.reverse))
        self.fields["relationship_type"].widget = forms.Select(
            choices=relationship_types)

        widget = ContactAutoComplete(
            attrs={
                'placeholder': _('Enter the name of a contact'),
                'size': '50',
                'class': 'colorbox'
            })
        self.fields["contact2"] = forms.CharField(label=_("Contact"),
                                                  widget=widget)
Esempio n. 11
0
 def __init__(self, *args, **kwargs):
     super(custom_form_class, self).__init__(*args, **kwargs)
     self.fields['favorite_language'].widget = forms.Select(
         choices=get_language_choices())
Esempio n. 12
0
class BaseCaseForm(mtforms.NonFieldErrorsClassFormMixin, forms.Form):
    """
    Base form for all test case/version forms.

    Provides self.user, tags and status fields, and non-field-errors-class
    mixin.

    """
    status = forms.CharField(
        widget=forms.Select(choices=model.CaseVersion.STATUS),
        initial=model.CaseVersion._meta.get_field("status").default,
        )
    add_tags = forms.CharField(
        widget=mtforms.AutocompleteInput(
            url=lambda: reverse("manage_tags_autocomplete")),
        required=False)
    idprefix = forms.CharField(max_length=200, required=False)
    priority = mtforms.MTChoiceField(
        choices=Choices("------", 1, 2, 3, 4),
        required=False
        )


    def __init__(self, *args, **kwargs):
        """Initialize form; pull out user from kwargs, set up data-allow-new."""
        self.user = kwargs.pop("user", None)

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

        self.fields["add_tags"].widget.attrs["data-allow-new"] = (
            "true"
            if (self.user and self.user.has_perm("tags.manage_tags"))
            else "false"
            )


    def clean(self):
        """Can't create new tags without appropriate permissions."""
        if (self.data.get("tag-newtag") and
                not (self.user and self.user.has_perm("tags.manage_tags"))):
            raise forms.ValidationError(
                "You do not have permission to create new tags.")
        return self.cleaned_data


    def save_new_tags(self, product=None):
        """Save new tags and add them to the list of tags to assign."""
        tags = self.cleaned_data.setdefault("tags", set())
        tags.update([int(tid) for tid in self.data.getlist("tag-tag")])

        new_tags = self.data.getlist("tag-newtag")

        for name in new_tags:
            # @@@ should pass in user here, need MTQuerySet.get_or_create
            t, created = model.Tag.objects.get_or_create(
                name=name, product=product)
            tags.add(t.id)


    def save_tags(self, caseversion):
        """Update set of tags assigned to ``caseversion``."""
        tags = self.cleaned_data.get("tags", set())

        current_tags = set([t.id for t in caseversion.tags.all()])
        caseversion.tags.add(*tags.difference(current_tags))
        caseversion.tags.remove(*current_tags.difference(tags))
Esempio n. 13
0
class NewEmailingForm(BsForm):
    """Form for creating a new emailing"""

    subscription_type = forms.IntegerField(label=_("Subscription Type"))
    newsletter = forms.IntegerField(label=_("Newsletter"))
    subject = forms.CharField(
        label=_("Subject"),
        required=False,
        widget=forms.TextInput(
            attrs={'placeholder': _('Subject of the newsletter')}))
    contacts = forms.CharField(widget=forms.HiddenInput())
    lang = forms.CharField(required=False,
                           label=_("Language"),
                           widget=forms.Select(choices=[('', _('Default'))] +
                                               list(settings.LANGUAGES)))
    from_email = forms.CharField(required=False, label=_("Sent from"))

    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()

    def get_contacts(self):
        """get the list of contacts stored by ids"""
        ids = self.cleaned_data["contacts"].split(";")
        return models.Contact.objects.filter(id__in=ids)

    def clean_subject(self):
        """subject validation"""
        newsletter_id = int(self.cleaned_data['newsletter'])
        subject = self.cleaned_data['subject']
        if newsletter_id == 0 and not subject:
            raise ValidationError(
                ugettext("Please enter a subject for the newsletter"))
        return subject

    def clean_subscription_type(self):
        """validation of subscription type. Return the subscription type object"""
        try:
            subscription_type = int(self.cleaned_data['subscription_type'])
            return SubscriptionType.objects.get(id=subscription_type)
        except (ValueError, KeyError, SubscriptionType.DoesNotExist):
            raise ValidationError(
                ugettext("Please select a valid subscription"))
Esempio n. 14
0
    def __init__(self, *args, **kwargs):
        # Configure the fieldset with dynamic fields
        fieldset_fields = self.Meta.fieldsets[-2][1]["fields"]
        for subscription_type in models.SubscriptionType.objects.all():
            field_name = "subscription_{0}".format(subscription_type.id)
            if field_name not in fieldset_fields:
                fieldset_fields.append(field_name)

        has_data = len(args) > 0
        super(ContactForm, self).__init__(*args, **kwargs)

        try:
            if self.instance and self.instance.entity and self.instance.entity.is_single_contact:
                self.fields['has_left'].widget = forms.HiddenInput()
        except models.Entity.DoesNotExist:
            pass

        self.fields["role"].help_text = _(
            "Select the roles played by the contact in his entity")

        if 'balafon.Profile' not in settings.INSTALLED_APPS:
            self.fields["accept_notifications"].widget = forms.HiddenInput()

        if has_data:
            self.fields.pop("email_verified")
        else:
            self.fields["email_verified"].widget.attrs['disabled'] = "disabled"

        # define the allowed gender
        gender_choices = [
            (models.Contact.GENDER_NOT_SET, '-------'),
            (models.Contact.GENDER_MALE, ugettext('Mr')),
            (models.Contact.GENDER_FEMALE, ugettext('Mrs')),
        ]
        if ALLOW_COUPLE_GENDER:
            gender_choices += [(models.Contact.GENDER_COUPLE,
                                ugettext('Mrs and Mr'))]
        self.fields['gender'].choices = gender_choices

        # create the dynamic fields
        for subscription_type in models.SubscriptionType.objects.all():
            field_name = "subscription_{0}".format(subscription_type.id)
            field = self.fields[field_name] = forms.BooleanField(
                label=subscription_type.name, required=False)
            if self.instance and self.instance.id:
                try:
                    subscription = models.Subscription.objects.get(
                        subscription_type=subscription_type,
                        contact=self.instance)
                    field.initial = subscription.accept_subscription
                except models.Subscription.DoesNotExist:
                    field.initial = False
            else:
                field.initial = get_subscription_default_value()

        if has_language_choices():
            self.fields['favorite_language'].widget = forms.Select(
                choices=get_language_choices(),
                attrs={'class': 'form-control'})
        else:
            self.fields['favorite_language'].widget = forms.HiddenInput()

        if not self.instance or not any([
                self.instance.lastname, self.instance.firstname,
                self.instance.email
        ]):
            # If the contact has not been created of not filled
            pass
            # keep the widget
            if len(args):
                # The form has been posted; we must initialize the list with allowed values
                contact_id = self.instance.id if self.instance else None
                post_data = args[0]
                lastname = post_data.get('lastname', '')
                firstname = post_data.get('firstname', '')
                email = post_data.get('email', '')
                same_as_contacts = get_suggested_same_as_contacts(
                    contact_id=contact_id,
                    lastname=lastname,
                    firstname=firstname,
                    email=email)
                self.fields['same_as_suggestions'].choices = [
                    (contact.id, '{0}'.format(contact))
                    for contact in same_as_contacts
                ]
        else:
            # hide the field
            self.fields['same_as_suggestions'].widget = forms.HiddenInput()
Esempio n. 15
0
class ContactForm(FormWithFieldsetMixin, ModelFormWithAddress):
    """Edit contact form"""
    same_as_suggestions = forms.ChoiceField(
        label=_('Same-as contacts'),
        choices=[],
        required=False,
        help_text=
        _('If this is a new contact for an existing person, you can link the different contacts between them'
          ),
        widget=forms.Select(
            attrs={
                'class': 'chosen-select',
                'data-placeholder': _('Select same-as contacts'),
                'style': "width: 100%;"
            }))

    class Meta:
        """form is defined from model"""
        model = models.Contact
        fields = ('gender', 'gender_title', 'lastname', 'firstname',
                  'birth_date', 'title', 'role', 'job', 'email', 'phone',
                  'mobile', 'favorite_language', 'street_number',
                  'street_type', 'address', 'address2', 'address3', 'zip_code',
                  'city', 'cedex', 'country', 'main_contact', 'email_verified',
                  'has_left', 'accept_notifications', 'photo',
                  'billing_street_number', 'billing_street_type',
                  'billing_address', 'billing_address2', 'billing_address3',
                  'billing_zip_code', 'billing_city', 'billing_cedex',
                  'billing_country', 'same_as_suggestions')
        widgets = {
            'notes':
            forms.Textarea(attrs={
                'placeholder': _('enter notes about the contact'),
                'cols': '72'
            }),
            'role':
            forms.SelectMultiple(
                attrs={
                    'class': 'chosen-select',
                    'data-placeholder': _('Select roles'),
                    'style': "width: 100%;"
                }),
        }
        fieldsets = [
            ('name', {
                'fields': [
                    'gender', 'gender_title', 'lastname', 'firstname', 'email',
                    'same_as_suggestions', 'phone', 'mobile'
                ],
                'legend':
                _('Name')
            }),
            ('web', {
                'fields': [
                    'birth_date',
                    'title',
                    'role',
                    'job',
                    'favorite_language',
                ],
                'legend':
                _('Contact details')
            }),
            ('address', {
                'fields': [
                    'street_number', 'street_type', 'address', 'address2',
                    'address3', 'zip_code', 'city', 'cedex', 'country'
                ],
                'legend':
                _('Address')
            }),
            ('billing_address', {
                'fields': [
                    'billing_street_number', 'billing_street_type',
                    'billing_address', 'billing_address2', 'billing_address3',
                    'billing_zip_code', 'billing_city', 'billing_cedex',
                    'billing_country'
                ],
                'legend':
                _('Billing address')
            }),
            ('relationship', {
                'fields': [
                    'main_contact', 'email_verified', 'has_left',
                    'accept_notifications'
                ],
                'legend':
                _('Options')
            }),
            ('photo', {
                'fields': ['photo'],
                'legend': _('Photo')
            }),
        ]

    def __init__(self, *args, **kwargs):
        # Configure the fieldset with dynamic fields
        fieldset_fields = self.Meta.fieldsets[-2][1]["fields"]
        for subscription_type in models.SubscriptionType.objects.all():
            field_name = "subscription_{0}".format(subscription_type.id)
            if field_name not in fieldset_fields:
                fieldset_fields.append(field_name)

        has_data = len(args) > 0
        super(ContactForm, self).__init__(*args, **kwargs)

        try:
            if self.instance and self.instance.entity and self.instance.entity.is_single_contact:
                self.fields['has_left'].widget = forms.HiddenInput()
        except models.Entity.DoesNotExist:
            pass

        self.fields["role"].help_text = _(
            "Select the roles played by the contact in his entity")

        if 'balafon.Profile' not in settings.INSTALLED_APPS:
            self.fields["accept_notifications"].widget = forms.HiddenInput()

        if has_data:
            self.fields.pop("email_verified")
        else:
            self.fields["email_verified"].widget.attrs['disabled'] = "disabled"

        # define the allowed gender
        gender_choices = [
            (models.Contact.GENDER_NOT_SET, '-------'),
            (models.Contact.GENDER_MALE, ugettext('Mr')),
            (models.Contact.GENDER_FEMALE, ugettext('Mrs')),
        ]
        if ALLOW_COUPLE_GENDER:
            gender_choices += [(models.Contact.GENDER_COUPLE,
                                ugettext('Mrs and Mr'))]
        self.fields['gender'].choices = gender_choices

        # create the dynamic fields
        for subscription_type in models.SubscriptionType.objects.all():
            field_name = "subscription_{0}".format(subscription_type.id)
            field = self.fields[field_name] = forms.BooleanField(
                label=subscription_type.name, required=False)
            if self.instance and self.instance.id:
                try:
                    subscription = models.Subscription.objects.get(
                        subscription_type=subscription_type,
                        contact=self.instance)
                    field.initial = subscription.accept_subscription
                except models.Subscription.DoesNotExist:
                    field.initial = False
            else:
                field.initial = get_subscription_default_value()

        if has_language_choices():
            self.fields['favorite_language'].widget = forms.Select(
                choices=get_language_choices(),
                attrs={'class': 'form-control'})
        else:
            self.fields['favorite_language'].widget = forms.HiddenInput()

        if not self.instance or not any([
                self.instance.lastname, self.instance.firstname,
                self.instance.email
        ]):
            # If the contact has not been created of not filled
            pass
            # keep the widget
            if len(args):
                # The form has been posted; we must initialize the list with allowed values
                contact_id = self.instance.id if self.instance else None
                post_data = args[0]
                lastname = post_data.get('lastname', '')
                firstname = post_data.get('firstname', '')
                email = post_data.get('email', '')
                same_as_contacts = get_suggested_same_as_contacts(
                    contact_id=contact_id,
                    lastname=lastname,
                    firstname=firstname,
                    email=email)
                self.fields['same_as_suggestions'].choices = [
                    (contact.id, '{0}'.format(contact))
                    for contact in same_as_contacts
                ]
        else:
            # hide the field
            self.fields['same_as_suggestions'].widget = forms.HiddenInput()

    def get_fieldsets(self):
        """return the list of fieldsets"""
        for fieldset in self.Meta.fieldsets:
            if fieldset[0] == 'billing_address' and not show_billing_address():
                # Ignore 'Billing address' tab if disable in settings
                continue
            yield fieldset

    def clean_photo(self):
        """photo validation"""
        photo = self.cleaned_data["photo"]
        instance = self.instance
        if not instance:
            instance = ""
            try:
                instance.id = models.Contact.objects.latest('id').id
            except models.Contact.DoesNotExist:
                instance.id = 1
        target_name = models.get_contact_photo_dir(instance, photo)
        if len(target_name) >= models.Contact._meta.get_field(
                'photo').max_length:
            raise ValidationError(ugettext("The file name is too long"))
        return photo

    def save_contact_subscriptions(self, contact):
        """save contact subscriptions"""
        for subscription_type in models.SubscriptionType.objects.all():
            field_name = "subscription_{0}".format(subscription_type.id)
            accept_subscription = self.cleaned_data[field_name]
            try:
                subscription = models.Subscription.objects.get(
                    contact=contact, subscription_type=subscription_type)
                if subscription.accept_subscription != accept_subscription:
                    subscription.accept_subscription = accept_subscription
                    subscription.save()
            except models.Subscription.DoesNotExist:
                if accept_subscription:
                    models.Subscription.objects.create(
                        contact=contact,
                        subscription_type=subscription_type,
                        accept_subscription=True)

    def clean_same_as_suggestions(self):
        contact_id = self.cleaned_data.get('same_as_suggestions', '')
        if contact_id:
            try:
                contact = models.Contact.objects.get(id=contact_id)
                return contact
            except models.Contact.DoesNotExist:
                raise ValidationError(ugettext("Contact does'nt exist"))

    def save_same_as(self, this_contact):
        contact = self.cleaned_data['same_as_suggestions']
        if contact:
            # if not found create one
            if not contact.same_as:
                this_contact.same_as = models.SameAs.objects.create()
                this_contact.same_as_priority = 2
                contact.same_as = this_contact.same_as
                contact.same_as_priority = 1
                contact.save()
            else:
                this_contact.same_as = contact.same_as
                this_contact.same_as_priority = contact.same_as.contact_set.count(
                ) + 1
            this_contact.save()

    def save(self, *args, **kwargs):
        """save"""
        contact = super(ContactForm, self).save(*args, **kwargs)
        if kwargs.get('commit', True):
            self.save_contact_subscriptions(contact)
            self.save_same_as(contact)
        return contact
Esempio n. 16
0
 class Meta(MessageForm.Meta):
     widgets = {
         'messageType': forms.Select(),
         'category': forms.CheckboxSelectMultiple(),
     }
Esempio n. 17
0
 def __init__(self, *args, **kwargs):
     super(custom_form_class, self).__init__(*args, **kwargs)
     self.fields['lang'].widget = forms.Select(
         choices=crm_settings.get_language_choices())
Esempio n. 18
0
class FoiRequestStatusForm(forms.Form):
    def __init__(self, foirequest, *args, **kwargs):
        super(FoiRequestStatusForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest
        self.fields['refusal_reason'] = forms.ChoiceField(
            label=_("Refusal Reason"),
            choices=[('', _('No or other reason given'))] +
            (foirequest.law.get_refusal_reason_choices()),
            required=False,
            widget=forms.Select(attrs={'class': 'form-control'}),
            help_text=
            _('When you are (partially) denied access to information, the Public Body should always state the reason.'
              ))

    status = forms.ChoiceField(
        label=_("Status"),
        widget=forms.RadioSelect,
        choices=[
            ('awaiting_response', _('This request is still ongoing.')),
            ('resolved', _('This request is finished.')),
            # ('request_redirected', _('This request has been redirected to a different public body.'))
        ])

    resolution = forms.ChoiceField(
        label=_('Resolution'),
        choices=[('', _('No outcome yet'))] +
        FoiRequest.RESOLUTION_FIELD_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text=_(
            'How would you describe the current outcome of this request?'))
    redirected = forms.IntegerField(
        label=_("Redirected to"),
        required=False,
        widget=PublicBodySelect,
        help_text=
        _('If your message is redirected to a different Public Body, please specify the new Public Body'
          ))
    if payment_possible:
        costs = forms.FloatField(
            label=_("Costs"),
            required=False,
            min_value=0.0,
            localize=True,
            widget=PriceInput,
            help_text=
            _('Please specify what the Public Body charges for the information.'
              ))

        def clean_costs(self):
            costs = self.cleaned_data['costs']
            if costs is None:
                return 0.0
            return costs

    def clean(self):
        pk = self.cleaned_data.get('redirected', None)
        status = self.cleaned_data.get('status', None)
        if status == "request_redirected":
            if pk is None:
                raise forms.ValidationError(
                    _("Provide the redirected public body!"))
            try:
                self._redirected_public_body = PublicBody.objects.get(id=pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
        if status == 'resolved':
            if not self.cleaned_data.get('resolution', ''):
                raise forms.ValidationError(
                    _('Please give a resolution to this request'))

        # if resolution is successful or partially_successful, set status to resolved
        if self.cleaned_data.get('resolution',
                                 '') in ('successful', 'partially_successful'):
            self.cleaned_data['status'] = 'resolved'

        return self.cleaned_data

    def set_status(self):
        data = self.cleaned_data
        status = data['status']
        resolution = data['resolution']
        foirequest = self.foirequest

        message = foirequest.message_needs_status()
        if message:
            message.status = status
            message.save()

        if status == "request_redirected":
            foirequest.due_date = foirequest.law.calculate_due_date()
            foirequest.public_body = self._redirected_public_body
            status = 'awaiting_response'

        foirequest.status = status
        foirequest.resolution = resolution

        foirequest.costs = data['costs']
        if resolution == "refused" or resolution == "partially_successful":
            foirequest.refusal_reason = data['refusal_reason']
        else:
            foirequest.refusal_reason = u""

        foirequest.save()

        status = data.pop("status")
        if status == 'resolved':
            foirequest.status_changed.send(sender=foirequest,
                                           status=resolution,
                                           data=data)
Esempio n. 19
0
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)
Esempio n. 20
0
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