Esempio n. 1
0
class MessageSideFilter(django_filters.FilterSet):
    """ Message list side filter """
    class Meta:
        model = Message
        fields = [
            'mtype',
            'category',
            'urgent',
            'q',
        ]

    mtype = django_filters.MultipleChoiceFilter(
        name='messageType',
        label=_("Message type"),
        choices=Message.TYPES_CHOICE,
        widget=forms.CheckboxSelectMultiple())

    category = django_filters.ModelMultipleChoiceFilter(
        name="category",
        label=_("Category"),
        widget=forms.CheckboxSelectMultiple(),
        queryset=Category.objects.all())

    urgent = django_filters.BooleanFilter(name="is_important",
                                          label=_("Urgent"),
                                          widget=forms.NullBooleanSelect())

    q = TitleMessageFilter(
        label=_("Keywords"),
        widget=forms.SearchInput(),
    )
Esempio n. 2
0
 class Meta:
     model = MailPreferences
     fields = ('subscription', 'wanted_actions', 'language', )
     widgets = {
         'wanted_actions': forms.CheckboxSelectMultiple(choices=(
             (status, actions_dict[status]) for status in settings.NOTIFICATIONS_EMAIL_PREFERENCES)
         )
     }
Esempio n. 3
0
class UserFilter(django_filters.FilterSet):
    """ Allow filtering user list """
    class Meta:
        model = User
        fields = ['category', 'q']
        order_by = (
            ('full_name', 'User Name'),
            ('date_joined', 'Date joined'),
        )

    category = django_filters.ModelMultipleChoiceFilter(
        name="category",
        label=_("Category"),
        widget=forms.CheckboxSelectMultiple(),
        queryset=Category.objects.all())

    q = django_filters.CharFilter(
        name='message',
        label=_("Keywords"),
        lookup_type="icontains",
        widget=forms.SearchInput(),
    )

    def get_order_by(self, order_value):
        if order_value == "full_name":
            return [
                "last_name",
                "first_name",
            ]
        return super(UserFilter, self).get_order_by(order_value)

    def get_ordering_field(self):
        if self._meta.order_by:
            if isinstance(self._meta.order_by, (list, tuple)):
                if isinstance(self._meta.order_by[0], (list, tuple)):
                    # e.g. (('field', 'Display name'), ...)
                    choices = [(f[0], f[1]) for f in self._meta.order_by]
                else:
                    choices = [
                        (f, _('%s (descending)' %
                              capfirst(f[1:])) if f[0] == '-' else capfirst(f))
                        for f in self._meta.order_by
                    ]
            else:
                # add asc and desc field names
                # use the filter's label if provided
                choices = []
                for f, fltr in self.filters.items():
                    choices.extend([
                        (fltr.name or f, fltr.label or capfirst(f)),
                        ("-%s" % (fltr.name or f),
                         _('%s (descending)' % (fltr.label or capfirst(f))))
                    ])
            return forms.ChoiceField(label="Ordering",
                                     required=False,
                                     choices=choices)
Esempio n. 4
0
class MapMessageFilter(django_filters.FilterSet):
    """ Main page map messages filter """
    class Meta:
        model = Message
        fields = [
            'mtype',
            'category',
        ]

    mtype = django_filters.MultipleChoiceFilter(
        name='messageType',
        label=_("Message type"),
        choices=Message.TYPES_CHOICE,
        widget=forms.CheckboxSelectMultiple())

    category = django_filters.ModelMultipleChoiceFilter(
        name="category",
        label=_("Category"),
        widget=forms.CheckboxSelectMultiple(),
        queryset=Category.objects.all())
Esempio n. 5
0
 class Meta:
     model = Message
     fields = (
         'title',
         'message',
         'messageType',
         'category',
         'address',
         'location',
         'is_anonymous',
         'allow_feedback',
         'is_virtual',
     )
     widgets = {
         'category': forms.CheckboxSelectMultiple(),
     }
Esempio n. 6
0
    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=[])
Esempio n. 7
0
 class Meta(MessageForm.Meta):
     widgets = {
         'messageType': forms.Select(),
         'category': forms.CheckboxSelectMultiple(),
     }
Esempio n. 8
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. 9
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