Example #1
0
class OrganizationPaymentForm(forms.ModelForm):
    disconnect_stripe_live = forms.BooleanField(required=False)
    disconnect_stripe_test = forms.BooleanField(required=False)

    class Meta:
        model = Organization
        fields = (
            'check_payment_allowed',
            'check_payable_to',
            'check_recipient',
            'check_address',
            'check_address_2',
            'check_city',
            'check_state_or_province',
            'check_zip',
            'check_country',
        )
        widgets = {
            'check_country': forms.Select,
        }

    def __init__(self, request, *args, **kwargs):
        super(OrganizationPaymentForm, self).__init__(*args, **kwargs)
        if not self.instance.stripe_live_connected():
            del self.fields['disconnect_stripe_live']
        if not self.instance.stripe_test_connected():
            del self.fields['disconnect_stripe_test']
        self.request = request
        if self.instance.pk is None:
            self.instance.owner = request.user

    def clean_check_payment_allowed(self):
        cpa = self.cleaned_data['check_payment_allowed']
        if cpa:
            for field in ('check_payable_to', 'check_recipient',
                          'check_address', 'check_city', 'check_zip',
                          'check_state_or_province', 'check_country'):
                self.fields[field].required = True
        return cpa

    def clean(self):
        cleaned_data = super(OrganizationPaymentForm, self).clean()
        if 'check_zip' in cleaned_data:
            country = self.instance.check_country
            code = cleaned_data['check_zip']
            try:
                cleaned_data['check_zip'] = clean_postal_code(country, code)
            except ValidationError, e:
                del cleaned_data['check_zip']
                self.add_error('check_zip', e)
        return cleaned_data
Example #2
0
class JobSearchForm(forms.Form):
    q = forms.CharField(
        label='What',
        required=False,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'job title, keywords or tags',
            }),
    )
    l = forms.CharField(
        label='Where',
        required=False,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'job title, keywords or tags',
            }),
    )

    is_visual_impairment_accepted = forms.BooleanField(
        label='visual disabilities', required=False, initial=False)
    is_hearing_impairment_accepted = forms.BooleanField(
        label='hearing disabilities', required=False, initial=False)
    is_motor_impairment_accepted = forms.BooleanField(
        label='motor disabilities', required=False, initial=False)

    def search(self, jobs):
        q = self.cleaned_data.get('q')
        if q:
            jobs = jobs.filter(title__icontains=q)

        l = self.cleaned_data.get('l')
        if l:
            jobs = jobs.filter(location__icontains=l)

        impairements_filter = {}
        for name in [
                'visual',
                'hearing',
                'motor',
        ]:
            impairment = 'is_{}_impairment_accepted'.format(name)
            value = self.cleaned_data.get(impairment)
            if value:
                impairements_filter[impairment] = value
        if impairements_filter:
            jobs = jobs.filter(**impairements_filter)

        return jobs
Example #3
0
class EditFragmentForm(BaseFragmentForm):
    """Edit fragment"""
    delete_me = floppyforms.BooleanField(label=_("delete"), required=False)

    class Meta:
        model = Fragment
        fields = (
            'type',
            'filter',
            'name',
            'css_class',
            'position',
        )
        widgets = {
            "type": forms.HiddenInput(),
            "filter": forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        if instance:
            instance.css_class = instance.css_class.split(" ")
        super(EditFragmentForm, self).__init__(*args, **kwargs)  # pylint: disable=E1002
        self.post_init()

    def save(self, *args, **kwargs):
        """delete """
        if self.cleaned_data['delete_me']:
            self.instance.delete()
            return None
        return super(EditFragmentForm, self).save(*args, **kwargs)  # pylint: disable=E1002
Example #4
0
class PostalReplyForm(PostalBaseForm):
    FIELD_ORDER = [
        'public_body', 'sender', 'date', 'subject', 'text', 'files',
        'not_publishable'
    ]
    PUBLIC_BODY_LABEL = _('Sender public body')

    sender = forms.CharField(
        label=_("Sender name"),
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _("Sender Name")
        }),
        required=True)

    not_publishable = forms.BooleanField(
        label=_("You are not allowed to publish some received documents"),
        initial=False,
        required=False,
        help_text=
        _('If the reply explicitly states that you are not allowed to publish some of the documents (e.g. due to copyright), check this.'
          ))

    def contribute_to_message(self, message):
        message.is_response = True
        message.sender_name = self.cleaned_data['sender']
        message.sender_public_body = message.request.public_body
        message.not_publishable = self.cleaned_data['not_publishable']
        return message
Example #5
0
class TermsForm(forms.Form):
    terms = forms.BooleanField(
        label=mark_safe(_("Terms and Conditions and Privacy Statement")),
        error_messages={
            'required':
            _('You need to accept our Terms and Conditions and Priavcy Statement.'
              )
        },
        widget=AgreeCheckboxInput(agree_to=_(
            u'You agree to our <a href="%(url_terms)s" class="target-new">Terms and Conditions</a> and <a href="%(url_privacy)s" class="target-new">Privacy Statement</a>'
        ),
                                  url_names={
                                      "url_terms": "help-terms",
                                      "url_privacy": "help-privacy"
                                  }))

    def __init__(self, *args, **kwargs):
        super(TermsForm, self).__init__(*args, **kwargs)
        if HAVE_NEWSLETTER():
            self.fields['newsletter'] = forms.BooleanField(
                required=False,
                label=_("Check if you want to receive our newsletter."))

    def save(self, user):
        user.terms = True
        if HAVE_NEWSLETTER():
            user.newsletter = self.cleaned_data['newsletter']
        user.save()
Example #6
0
class OneTimePaymentForm(BasePaymentForm, AddCardForm):
    save_card = forms.BooleanField(required=False)

    def __init__(self, order, *args, **kwargs):
        super(OneTimePaymentForm, self).__init__(order=order,
                                                 api_type=order.event.api_type,
                                                 *args,
                                                 **kwargs)
        if not self.user.is_authenticated():
            del self.fields['save_card']

    def _post_clean(self):
        kwargs = {
            'amount': self.amount,
            'event': self.order.event,
            'order': self.order,
        }
        try:
            if self.cleaned_data.get('save_card'):
                self.card = self.add_card(self.cleaned_data['token'])
                self._charge = stripe_charge(self.card.id,
                                             customer=self.customer,
                                             **kwargs)
            else:
                self._charge = stripe_charge(self.cleaned_data['token'],
                                             **kwargs)
                self.card = self._charge.source
        except stripe.error.CardError, e:
            self.add_error(None, e.message)
        except stripe.error.APIError, e:
            self.add_error(None, STRIPE_API_ERROR)
Example #7
0
 def __init__(self, *args, **kwargs):
     super(PermissionsForm, self).__init__(*args, **kwargs)
     for role in Group.objects.all():
         for feature in models.Feature.objects.all():
             for permission in feature.permissions.all():
                 is_enabled = role.permissions.filter(
                     pk=permission.pk).exists()
                 name = '-'.join((role.name, feature.name, permission.name))
                 checkbox = forms.BooleanField(
                     required=False,
                     initial=is_enabled,
                 )
                 checkbox.role = role
                 checkbox.permission = permission
                 self.fields[name] = checkbox
     for feature in models.Feature.objects.all():
         for permission in feature.permissions.all():
             users = User.objects.filter(
                 user_permissions=permission).values_list('username',
                                                          flat=True)
             users = '|'.join(users)
             name = '%s-%s' % (permission.content_type_id,
                               permission.codename)
             self.fields[name] = forms.CharField(required=False,
                                                 initial=users)
             self.fields[name].permission = permission
Example #8
0
class StudentWorkUpdatePublicForm(ParticipationCheckHiddenFormMixin,
                                  forms.ModelForm):
    text = forms.CharField(widget=FroalaEditor)
    republish = forms.BooleanField(required=False)

    class Meta:
        model = StudentsWork
        fields = ('title', 'text')
Example #9
0
 def __init__(self, user, *args, **kwargs):
     super(UserChangeForm, self).__init__(*args, **kwargs)
     self.user = user
     self.fields['address'].initial = self.user.address
     self.fields['email'].initial = self.user.email
     if HAVE_NEWSLETTER():
         self.fields['newsletter'] = forms.BooleanField(
             required=False, label=_("Newsletter"))
         self.fields['newsletter'].initial = self.user.newsletter
     self.order_fields(self.field_order)
Example #10
0
class PhotoGrid(forms.ModelForm):
    fastUpload = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'fastUploadClass'}),
        required=False,
        initial=False)

    #rodalref = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class': 'boolRodRef'}), required=False)
    class Meta:
        model = Report
        fields = ('hide', )
class SimpleForm(forms.Form):
    name = forms.CharField(
        max_length=64, widget=widgets.TextInput(attrs={"placeholder": "Jane Doe"})
    )
    email = forms.CharField(
        max_length=128,
        widget=widgets.TextInput(attrs={"placeholder": "*****@*****.**"}),
    )
    tos = forms.BooleanField(
        label="", widget=SwitchInput(), help_text="Terms of Service"
    )
Example #12
0
 def __init__(self, *args, **kwargs):
     super(InteractionsForm, self).__init__(*args, **kwargs)
     grid = utils.get_role_grid()
     for role1, others in grid:
         for role2 in others:
             for interaction in models.Interaction.objects.all():
                 is_permitted = interaction.is_permitted(role1, role2)
                 name = '-'.join((interaction.name, role1, role2))
                 checkbox = forms.BooleanField(
                     required=False,
                     initial=is_permitted,
                 )
                 checkbox.interaction = interaction
                 checkbox.role1 = Group.objects.get(name=role1)
                 checkbox.role2 = Group.objects.get(name=role2)
                 self.fields[name] = checkbox
Example #13
0
class EULAForm(forms.Form):
    """ Formulaire de validation des CGU """

    # Constantes
    CHOICES = ((False, _("I refuse to comply to the EULA and do not want to use this website")),
               (True, _("I abide to the {website} EULA").format(website=get_website_name()))
               )

    # Champs
    eula = forms_.BooleanField(required=True, label=_("EULA"), widget=forms.Select(choices=CHOICES))

    # Initialiseur
    def __init__(self, *args, **kwargs):
        """ Initialiser le formulaire """
        super(EULAForm, self).__init__(*args, **kwargs)
        self.fields['eula'].error_messages = {'required': _("You must abide to the EULA to continue")}
Example #14
0
class SubscribeContactsAdminForm(SearchActionForm):
    """This form is used for superuser forcing newsletter subscription"""
    subscription_type = forms.ChoiceField(required=True)
    subscribe = forms.BooleanField(
        required=False, label=_('Subscribe'), help_text=_('It will subscribe/unsubscribe all selected contacts')
    )

    def __init__(self, *args, **kwargs):
        super(SubscribeContactsAdminForm, self).__init__(*args, **kwargs)
        self.fields['subscription_type'].choices = [
            (subscription_type.id, subscription_type.name)
            for subscription_type in SubscriptionType.objects.all()
        ]

    def clean_subscription_type(self):
        try:
            return SubscriptionType.objects.get(id=self.cleaned_data['subscription_type'])
        except SubscriptionType.DoesNotExist:
            raise ValidationError(_('Unknown subscription type'))
Example #15
0
class CancelLinesForm(forms.Form):
    verify_ok = forms.BooleanField(initial=True, widget=forms.HiddenInput)

    def clean_verify_ok(self):
        if self.cleaned_data.get('verify_ok') is not True:
            raise ValidationError(
                _("Je moet goedkeuring geven om alle lijnen op te heffen"))

    def __init__(self, *args, **kwargs):
        super(CancelLinesForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = 'journey_redbutton'
        self.helper.layout = Layout(
            Hidden('verify_ok', 'true'),
            Submit(
                'submit',
                _("Hef alle ritten op"),
                css_class="text-center btn-danger btn-tall col-sm-3 pull-right"
            ))
Example #16
0
class SubscriptionForm(forms.Form):
    subscribe = forms.BooleanField(label=_('Subscribe?'), required=False)
    name = forms.CharField(label=_('Name'), required=False)
    url = forms.URLField(label=_('URL'))
    category = forms.ChoiceField(label=_('Category'), required=False)

    def clean_url(self):
        url = self.cleaned_data['url']
        if (self.cleaned_data.get('subscribe', False)
                and self.user.feeds.filter(url=url).exists()):
            raise forms.ValidationError(
                _("You are already subscribed to this feed."))
        return url

    def clean_name(self):
        if (self.cleaned_data.get('subscribe', False)
                and not self.cleaned_data['name']):
            raise forms.ValidationError(_('This field is required.'))
        return self.cleaned_data['name']
Example #17
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)
Example #18
0
class LessonCopyForm(forms.Form):
    copy_lessonsteps = forms.ModelMultipleChoiceField(
        queryset=None,
        widget=CheckboxSelectMultiple,
        required=False
    )
    copy_lesson = forms.BooleanField(
        required=False
    )

    def __init__(self, *args, **kwargs):
        lesson_pk = kwargs.pop('lesson_pk', None)
        self.lesson = get_object_or_404(Lesson, pk=lesson_pk)

        super(LessonCopyForm, self).__init__(*args, **kwargs)
        self.fields['copy_lessonsteps'].queryset = self.lesson.get_children()

    def clean(self):
        if not self.cleaned_data['copy_lesson']:
            if (self.cleaned_data['copy_lessonsteps'] == []):
                raise ValidationError('''Bitte etwas zum Kopieren auswählen!''')
Example #19
0
    def __init__(self, foirequest, *args, **kwargs):
        super(SendMessageForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest

        choices = [(0, _("Default address of %(publicbody)s") % {
            "publicbody": foirequest.public_body.name
        })]
        choices.extend([
            (m.id, m.reply_address_entry)
            for k, m in foirequest.possible_reply_addresses().items()
        ])
        self.fields['to'].choices = choices

        if foirequest.law and foirequest.law.email_only:
            self.fields['send_address'] = forms.BooleanField(
                label=_("Send physical address"),
                help_text=(_(
                    'If the public body is asking for your post '
                    'address, check this and we will append it to your message.'
                )),
                required=False)
Example #20
0
class RegistrationForm(forms.Form):
    honeypot = forms.CharField(required=False, widget=forms.HiddenInput)
    firstname = forms.CharField(label=_('Your first name?'))
    lastname = forms.CharField(label=_('Your last name:'))
    username = forms.CharField(max_length=30)
    password = forms.CharField(
        widget=forms.PasswordInput,
        help_text=_('Make sure to use a secure password.'),
    )
    password2 = forms.CharField(label=_('Retype password'), widget=forms.PasswordInput)
    age = forms.IntegerField(required=False)
    height = forms.DecimalField(localize=True, required=False)
    agree_to_terms = forms.BooleanField()

    def clean_honeypot(self):
        if self.cleaned_data.get('honeypot'):
            raise ValidationError('Haha, you trapped into the honeypot.')
        return self.cleaned_data['honeypot']

    def clean(self):
        if self.errors:
            raise ValidationError('Please correct the errors below.')
Example #21
0
class BaseAddCaseForm(forms.Form):
    """Base form for adding cases."""
    product = mtforms.MTModelChoiceField(
        model.Product.objects.all(),
        choice_attrs=lambda p: {"data-product-id": p.id},
        )
    productversion = mtforms.MTModelChoiceField(
        queryset=model.ProductVersion.objects.all(),
        choice_attrs=mtforms.product_id_attrs,
        label_from_instance=lambda pv: pv.version,
        )
    and_later_versions = forms.BooleanField(initial=True, required=False)


    def __init__(self, *args, **kwargs):
        """Initialize form; possibly add suite field."""
        super(BaseAddCaseForm, self).__init__(*args, **kwargs)

        if self.user and self.user.has_perm("library.manage_suite_cases"):
            self.fields["suite"] = mtforms.MTModelChoiceField(
                model.Suite.objects.all(),
                choice_attrs=mtforms.product_id_attrs,
                required=False)


    def clean(self):
        """Verify that products all match up."""
        productversion = self.cleaned_data.get("productversion")
        suite = self.cleaned_data.get("suite")
        product = self.cleaned_data.get("product")
        if product and productversion and productversion.product != product:
            raise forms.ValidationError(
                "Must select a version of the correct product.")
        if product and suite and suite.product != product:
            raise forms.ValidationError(
                "Must select a suite for the correct product.")
        return self.cleaned_data
Example #22
0
    def __init__(self, user, bt_ids, submit, *args, **kwargs):
        super(BankTransactionListForm, self).__init__(*args, **kwargs)

        self.fields['tags'].queryset = (
            BankTransactionTag.objects.get_user_tags_queryset(user))
        self.fields['reconciled'].widget.choices[0] = ('1', _('Reconciled?'))

        for pk in bt_ids:
            self.fields['banktransaction_' + str(pk)] = forms.BooleanField(
                required=False,
                widget=forms.CheckboxInput(attrs={'data-id': pk}))

        choices = ()
        if user.has_perm('banktransactions.change_banktransaction'):
            choices += (
                ('reconcile', _('Reconcile')),
                ('unreconcile', _('Unreconcile')),
            )
        if user.has_perm('banktransactions.delete_banktransaction'):
            choices += (('delete', _('Delete')), )
        if choices:
            self.fields['operation'].choices = choices

        self._submit = submit
Example #23
0
 def __init__(self, *args, **kwargs):
     super(VirtualMessageFormMixin, self).__init__(*args, **kwargs)
     self.fields['is_virtual'] = forms.BooleanField(default=True)
Example #24
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)
Example #25
0
class BankTransactionTagCreateForm(BankTransactionTagForm):

    redirect = forms.BooleanField(label=_('Stay on page?'), required=False)
Example #26
0
class RequestForm(forms.Form):
    public_body = forms.CharField(
        widget=PublicBodySelect,
        label=_("Search for a topic or a public body:"),
        required=False)
    subject = forms.CharField(
        label=_("Subject"),
        max_length=230,
        widget=forms.TextInput(attrs={
            'placeholder': _("Subject"),
            "class": "form-control"
        }))
    body = forms.CharField(
        label=_("Body"),
        widget=forms.Textarea(
            attrs={
                'placeholder': _("Specify your request here..."),
                "class": "form-control"
            }))
    full_text = forms.BooleanField(
        required=False,
        initial=False,
        label=_("Don't wrap in template"),
        widget=forms.CheckboxInput(attrs={'tabindex': '-1'}))
    public = forms.BooleanField(
        required=False,
        initial=True,
        label=_("This request is public."),
        help_text=_(
            "If you don't want your request to be public right now,"
            " uncheck this. You can always decide to make it public later."))
    reference = forms.CharField(widget=forms.HiddenInput, required=False)
    redirect_url = forms.CharField(widget=forms.HiddenInput, required=False)
    hide_public = forms.BooleanField(widget=forms.HiddenInput,
                                     initial=False,
                                     required=False)
    hide_similar = forms.BooleanField(widget=forms.HiddenInput,
                                      initial=False,
                                      required=False)

    def __init__(self,
                 user=None,
                 list_of_laws=(),
                 default_law=None,
                 hide_law_widgets=True,
                 **kwargs):
        super(RequestForm, self).__init__(**kwargs)
        self.user = user
        self.list_of_laws = list_of_laws
        self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws])
        self.default_law = default_law

        self.fields["public_body"].widget.set_initial_jurisdiction(
            kwargs.get('initial', {}).pop('jurisdiction', None))
        self.fields["public_body"].widget.set_initial_search(
            kwargs.get('initial', {}).pop('public_body_search', None))
        self.fields["law"] = forms.ChoiceField(
            label=_("Information Law"),
            required=False,
            widget=forms.Select if not hide_law_widgets else forms.HiddenInput,
            initial=default_law.pk,
            choices=((l.pk, l.name) for l in list_of_laws))

    def laws_to_json(self):
        return json.dumps(
            dict([(l.id, l.as_dict()) for l in self.list_of_laws]))

    def clean_public_body(self):
        pb = self.cleaned_data['public_body']
        if pb == "new":
            if not new_publicbody_allowed:
                raise forms.ValidationError(
                    _("You are not allowed to create a new public body"))
        elif pb == "":
            if not publicbody_empty:
                raise forms.ValidationError(
                    _("You must specify a public body"))
            pb = None
        else:
            try:
                pb_pk = int(pb)
            except ValueError:
                raise forms.ValidationError(_("Invalid value"))
            try:
                public_body = PublicBody.objects.get(pk=pb_pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
            self.public_body_object = public_body
            self.foi_law_object = public_body.default_law
        return pb

    public_body_object = None

    def clean_reference(self):
        ref = self.cleaned_data['reference']
        if not ref:
            return ''
        try:
            kind, value = ref.split(':', 1)
        except ValueError:
            return ''
        try:
            return '%s:%s' % (kind, value)
        except ValueError:
            return ''

    def clean_law_for_public_body(self, public_body):
        law = self.clean_law_without_public_body()
        if law is None:
            return None
        if law.jurisdiction.id != public_body.jurisdiction.id:
            self._errors["law"] = self.error_class(
                [_("Invalid Information Law")])
            return None
        return law

    def clean_law_without_public_body(self):
        try:
            law = self.cleaned_data['law']
            law = self.indexed_laws[int(law)]
        except (ValueError, KeyError):
            self._errors["law"] = self.error_class(
                [_("Invalid Information Law")])
            return None
        return law

    def clean(self):
        cleaned = self.cleaned_data
        public_body = cleaned.get("public_body")
        if public_body is not None and (public_body != "new"
                                        and public_body != ""):
            self.foi_law = self.clean_law_for_public_body(
                self.public_body_object)
        else:
            self.foi_law = self.clean_law_without_public_body()

        throttle_message = check_throttle(self.user, FoiRequest)
        if throttle_message:
            raise forms.ValidationError(throttle_message)

        return cleaned
Example #27
0
class HostingForm(MemoModelForm, CustomDataForm):
    providing_housing = forms.BooleanField(initial=False, required=False)
    save_as_defaults = forms.BooleanField(
        initial=True,
        required=False,
        label="Remember this information for future events.",
        help_text="You will still be able to modify it later.")

    class Meta:
        model = EventHousing
        exclude = ('event', 'home', 'order')
        widgets = {'country': forms.Select}

    def __init__(self, *args, **kwargs):
        super(HostingForm, self).__init__({}, *args, **kwargs)

        self.initial.update(
            {'providing_housing': self.instance.order.providing_housing})
        person = self.instance.order.person
        event = self.instance.event
        if person is None:
            del self.fields['save_as_defaults']

        if self.instance.pk is None:
            if person is not None:
                self.initial.update({
                    'contact_name': person.get_full_name(),
                    'contact_email': person.email,
                })
            home = self.instance.home
            if home is not None:
                self.initial.update({
                    'address':
                    home.address,
                    'address_2':
                    home.address_2,
                    'city':
                    home.city,
                    'state_or_province':
                    home.state_or_province,
                    'zip_code':
                    home.zip_code,
                    'country':
                    home.country,
                    'public_transit_access':
                    home.public_transit_access,
                    'ef_present':
                    self.filter(EnvironmentalFactor.objects.only('id'),
                                home_present=home),
                    'ef_avoid':
                    self.filter(EnvironmentalFactor.objects.only('id'),
                                home_avoid=home),
                    'person_prefer':
                    home.person_prefer,
                    'person_avoid':
                    home.person_avoid,
                    'housing_categories':
                    self.filter(HousingCategory.objects.only('id'),
                                homes=home),
                })
            else:
                self.initial.update({
                    'city': event.city,
                    'state_or_province': event.state_or_province,
                    'country': event.country,
                })
        self.set_choices('ef_present',
                         EnvironmentalFactor.objects.only('id', 'name'))
        self.set_choices('ef_avoid',
                         EnvironmentalFactor.objects.only('id', 'name'))
        self.set_choices('housing_categories',
                         HousingCategory.objects.only('id', 'name'))

        self.nights = self.filter(HousingRequestNight,
                                  date__gte=event.start_date -
                                  datetime.timedelta(1),
                                  date__lte=event.end_date)
        slot_map = {}
        if self.instance.pk is not None:
            slot_map = {
                slot.date: slot
                for slot in self.filter(HousingSlot,
                                        eventhousing=self.instance)
            }

        data = None if not self.is_bound else self.data
        self.slot_forms = []
        for night in self.nights:
            if night.date in slot_map:
                instance = slot_map[night.date]
            else:
                instance = HousingSlot(eventhousing=self.instance,
                                       date=night.date)

            self.slot_forms.append(
                HousingSlotForm(instance=instance,
                                data=data,
                                prefix='{}-{}'.format(self.prefix, night.pk)))

    def get_custom_forms(self):
        return self.instance.event.forms.filter(
            form_type=CustomForm.HOSTING).prefetch_related('fields')

    def clean(self):
        cleaned_data = super(HostingForm, self).clean()
        if 'country' in cleaned_data and 'zip_code' in cleaned_data:
            country = cleaned_data['country']
            code = cleaned_data['zip_code']
            try:
                cleaned_data['zip_code'] = clean_postal_code(country, code)
            except ValidationError, e:
                del cleaned_data['zip_code']
                self.add_error('zip_code', e)
        return cleaned_data
Example #28
0
class RunForm(mtforms.NonFieldErrorsClassFormMixin, mtforms.MTModelForm):
    """Base form for adding/editing runs."""
    suites = mtforms.MTMultipleChoiceField(
        required=False,
        widget=mtforms.FilteredSelectMultiple(
            choice_template="manage/run/suite_select/_suite_select_item.html",
            listordering_template=(
                "manage/run/suite_select/_suite_select_listordering.html"),
            filters=[
                filters.KeywordFilter("name"),
                filters.ModelFilter(
                    "author", queryset=model.User.objects.all()),
                ],
            )
        )
    productversion = mtforms.MTModelChoiceField(
        queryset=model.ProductVersion.objects.all(),
        choice_attrs=mtforms.product_id_attrs,
        )
    build = forms.CharField(max_length=200, required=False)
    is_series = forms.BooleanField(required=False)


    class Meta:
        model = model.Run
        fields = [
            "productversion",
            "name",
            "description",
            "is_series",
            "build",
            "start",
            "end",
            "is_series",
            ]
        widgets = {
            "name": forms.TextInput,
            "description": mtforms.BareTextarea,
            "build": forms.TextInput,
            "is_series": forms.CheckboxInput,
            "start": forms.DateInput,
            "end": forms.DateInput,
            }


    def clean_suites(self):
        """
        Make sure all the ids for the suites are valid and populate
        self.cleaned_data with the real objects.

        If these are not ids, then they are read-only strings of the title
        and therefore don't need to be validated.  So first verify they're
        all ints.
        """

        try:
            suites = dict((unicode(x.id), x) for x in
                model.Suite.objects.filter(pk__in=self.cleaned_data["suites"]))
            try:
                return [suites[x] for x in self.cleaned_data["suites"]]

            except KeyError as e:
                raise ValidationError("Not a valid suite for this run.")

        except ValueError:
            # some of the values weren't ints, and therefore this is
            # from the read-only list of suites.  so return None so that we
            # don't try to remove and re-add them.
            if "suites" in self.changed_data:  # pragma: no cover
                self.changed_data.remove("suites")
            return None


    def clean_build(self):
        """If this is a series, then null out the build field."""
        if self.cleaned_data["is_series"]:
            return None


    def save(self, user=None):
        """Save and return run, with suite associations."""
        user = user or self.user
        run = super(RunForm, self).save(user=user)

        if "suites" in self.changed_data:
            # if this is empty, then don't make any changes, because
            # either there are no suites, or this came from the read
            # only suite list.
            run.runsuites.all().delete(permanent=True)
            for i, suite in enumerate(self.cleaned_data["suites"]):
                model.RunSuite.objects.create(
                    run=run, suite=suite, order=i, user=user)

        return run
Example #29
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()
Example #30
0
class EventCreateForm(forms.ModelForm):
    template_event = forms.ModelChoiceField(queryset=Event.objects.all(),
                                            required=False)
    new_organization_name = forms.CharField(required=False)
    new_organization_slug = forms.SlugField(required=False)
    create_new_organization = forms.BooleanField(required=False)
    organization = forms.ModelChoiceField(queryset=Organization.objects.all(),
                                          required=False)

    class Meta:
        model = Event
        fields = ('name', 'slug', 'start_date', 'end_date', 'start_time',
                  'end_time')

    def __init__(self, request, *args, **kwargs):
        super(EventCreateForm, self).__init__(*args, **kwargs)
        self.request = request
        if not request.user.is_authenticated():
            raise ValueError("EventCreateForm requires an authenticated user.")
        self.fields['template_event'].queryset = Event.objects.filter(
            Q(organization__members=request.user)
            | Q(members=request.user)).order_by('-last_modified').distinct()
        self.fields['organization'].queryset = Organization.objects.filter(
            organizationmember__person=request.user,
            organizationmember__role__in=(
                OrganizationMember.OWNER,
                OrganizationMember.EDIT,
            )).order_by('name').distinct()
        self.initial['create_new_organization'] = not self.fields[
            'organization'].queryset

    def clean(self):
        cd = super(EventCreateForm, self).clean()
        if ('start_date' in cd and 'end_date' in cd
                and cd['start_date'] > cd['end_date']):
            self.add_error(
                'start_date',
                "Start date must be before or equal to the end date.")

        if (cd.get('template_event') and cd.get('organization') and
                cd['template_event'].organization_id != cd['organization'].id):
            self.add_error(
                'template_event',
                "Template event and new event must be from the same organization."
            )

        if cd.get('create_new_organization'):
            if cd.get('new_organization_slug'):
                if Organization.objects.filter(
                        slug=cd['new_organization_slug']).exists():
                    self.add_error(
                        'new_organization_slug',
                        'URL is already in use by another organization; please choose a different one.'
                    )
            else:
                self.add_error('new_organization_slug',
                               'New organization requires a URL.')

            if not cd.get('new_organization_name'):
                self.add_error('new_organization_name',
                               'New organization requires a URL.')
        else:
            if not cd.get('organization'):
                self.add_error('organization', 'Organization is required.')
            elif cd.get('slug'):
                if Event.objects.filter(organization=cd['organization'],
                                        slug=cd['slug']).exists():
                    self.add_error(
                        'slug',
                        'URL is already in use by another event; please choose a different one.'
                    )

        return cd

    def _adjust_date(self, old_event, new_event, date):
        """
        Returns a date relative to the new event's start date as the given date
        is relative to the olde event's start date.

        """
        return date + (new_event.start_date - old_event.start_date)

    def save(self):
        if self.cleaned_data.get('create_new_organization'):
            self.instance.organization = Organization.objects.create(
                name=self.cleaned_data['new_organization_name'],
                slug=self.cleaned_data['new_organization_slug'],
            )
            OrganizationMember.objects.create(
                organization=self.instance.organization,
                person=self.request.user,
                role=OrganizationMember.OWNER,
            )
        else:
            self.instance.organization = self.cleaned_data['organization']

        if self.instance.is_demo():
            self.instance.api_type = Event.TEST

        self.instance.application_fee_percent = self.instance.organization.default_application_fee_percent

        template = self.cleaned_data.get('template_event')
        if template:
            fields = (
                'description',
                'website_url',
                'banner_image',
                'city',
                'state_or_province',
                'country',
                'timezone',
                'currency',
                'has_dances',
                'has_classes',
                'liability_waiver',
                'privacy',
                'collect_housing_data',
                'collect_survey_data',
                'cart_timeout',
                'check_postmark_cutoff',
                'transfers_allowed',
                'facebook_url',
            )
            for field in fields:
                setattr(self.instance, field, getattr(template, field))

        instance = super(EventCreateForm, self).save()

        if template:
            items = Item.objects.filter(event=template).prefetch_related(
                'options', 'images')
            for item in items:
                options = list(item.options.all())
                images = list(item.images.all())
                item.pk = None
                item.event = instance
                item.save()
                for option in options:
                    option.pk = None
                    option.item = item
                    option.available_start = self._adjust_date(
                        template, instance, option.available_start)
                    option.available_end = self._adjust_date(
                        template, instance, option.available_end)
                ItemOption.objects.bulk_create(options)
                for image in images:
                    image.pk = None
                    image.item = item
                ItemImage.objects.bulk_create(images)

            discounts = list(Discount.objects.filter(event=template))
            for discount in discounts:
                discount.pk = None
                discount.event = instance
                discount.available_start = self._adjust_date(
                    template, instance, discount.available_start)
                discount.available_end = self._adjust_date(
                    template, instance, discount.available_end)
            Discount.objects.bulk_create(discounts)

            saved_reports = list(SavedReport.objects.filter(event=template))
            for saved_report in saved_reports:
                saved_report.pk = None
                saved_report.event = instance
            SavedReport.objects.bulk_create(saved_reports)

            forms = CustomForm.objects.filter(
                event=template).prefetch_related('fields')
            for form in forms:
                fields = list(form.fields.all())
                form.pk = None
                form.event = instance
                form.save()
                for field in fields:
                    field.pk = None
                    field.form = form
                CustomFormField.objects.bulk_create(fields)
        return instance