class PhpbbSetPasswordForm(SetPasswordForm):

    def __init__(self, *args, **kwargs):

        self.helper = FormHelper()
        self.helper.form_class = 'well form-horizontal'
        self.helper.form_method = 'post'
        self.helper.add_input(Submit('submit', _(u'Change password'), css_class='btn btn-danger'))
        super(PhpbbSetPasswordForm, self).__init__(*args, **kwargs)

    def save(self):

        new_user = super(PhpbbSetPasswordForm, self).save(commit=False)

        password = self.cleaned_data['new_password1']
        phpbb_user = new_user.get_profile().phpbb_user

        pass_md5 = hashlib.md5(password).hexdigest()
        phpbb_user.user_password = pass_md5
        # is this nessesary ?
        phpbb_user.save()
        # commit again
        new_user.save()        
        
        return new_user
Exemple #2
0
class ImageFormCrispy(forms.ModelForm):
    class Meta(object):
        model = Image
        exclude = ('user', 'order', 'album', 'status_changed',
                   )
        fields = ['content_type', 'object_pk', 'image', 'status']
        widgets = {
            'status': forms.HiddenInput(),
            'content_type': forms.HiddenInput(),
            'object_pk': forms.HiddenInput(),

            }
    #content_type = forms.CharField(widget=forms.HiddenInput())
    #object_pk = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, user, content_type=None, object_pk=None, *args, **kwargs):
        super(ImageFormCrispy, self).__init__(*args, **kwargs)
        self.fields['status'].initial = 'public'
        if content_type:
            self.fields['content_type'].initial = content_type
        if object_pk:
            self.fields['object_pk'].initial = object_pk
        if AUTOCOMPLETE_LIGHT_INSTALLED:
            self.fields['tags'].widget = autocomplete_light.TextWidget('TagAutocomplete')
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_class = 'form-horizontal'
        self.helper.form_action = 'imagestore:upload'
        self.helper.add_input(Submit('submit', 'Submit'))
Exemple #3
0
class ImportCreateForm(forms.Form):
    
    def __init__(self, *args, **kwargs):
        super(ImportCreateForm, self).__init__(*args, **kwargs)        
        
        self.helper = FormHelper()
        self.helper.form_id = "bulk_edit%s" % 'asd'
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = ''
        self.helper.form_tag = True
        """"""
        layout = Layout(

              Field('agree_terms'),
              Field('agree_documentation'),
  
            FormActions(
                Submit('submit', 'Continue', css_class='btn btn-primary')
            ),
        )
        self.helper.add_layout(layout)
    
    agree_terms = forms.BooleanField(
        label = _('I agree to the Terms & Conditions'),
        initial = False,
        required = True,
    )

    agree_documentation = forms.BooleanField(
        label = _('I read the ducumentation and know how Importing works'),
        initial = False,
        required = True,
    )
Exemple #4
0
    def __init__(self, *args, **kwargs):
        super(KnoWhereLoginForm, self).__init__(*args, **kwargs)
        self.fields['password'].widget = forms.PasswordInput()

        helper = FormHelper()
        helper.add_input(Submit('submit', 'Login'))
        self.helper = helper
Exemple #5
0
class PasswordForm(PasswordChangeForm):
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'

        self.helper.add_input(Submit('submit', 'Submit'))
        super(PasswordForm, self).__init__(*args, **kwargs)
Exemple #6
0
class ExampleForm(forms.Form):

    nama = forms.CharField(
        label = "Nama Anda",
        max_length = 80,
        required = True,
    )

    email = forms.EmailField(
        label = "Email Anda",
        max_length = 80,
        required = True,
    )

    pesanan = forms.CharField(
        label = "Pesanan Anda.",
        required = False,
        widget = forms.Textarea,
    )

    komentar = forms.CharField(
        label = "Komentar tambahan untuk kami.",
        required = False,
        widget = forms.Textarea,
    )
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id = "id-exampleForm"
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'

        self.helper.add_input(Submit('submit', 'Kirimkan pesanan'))
        super(ExampleForm,self).__init__(*args, **kwargs)
Exemple #7
0
class ActaForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ActaForm, self).__init__(*args, **kwargs)

        current_subasta = Subasta.objects.get_current()

        # Mostrar solo las personas inscriptas
        self.fields['persona'].queryset = current_subasta.personas.all()

        # Mostrar solo los profesionales de la subasta
        self.fields['profesionales'].queryset = current_subasta.profesionales.all()

        self.helper = FormHelper()
        self.helper.form_method = "POST"
        self.helper.form_action = reverse("subastas:actas_create")
        self.helper.add_input(Submit('job_submit', 'Guardar'))
        self.helper.add_input(Reset('job_reset', 'Limpiar',
                              css_class='btn-default'))
        self.helper.layout = Layout(
            Div('lote',
                'persona',
                'profesionales',
                'descripcion')
        )

    class Meta:
        fields = ['lote',
                  'persona',
                  'profesionales',
                  'descripcion']
        model = Acta
Exemple #8
0
def notification_settings(request):
    forms = []
    for plugin in plugins.all():
        for form in safe_execute(plugin.get_notification_forms) or ():
            form = safe_execute(form, plugin, request.user, request.POST or None)
            if not form:
                continue
            helper = FormHelper()
            helper.form_tag = False
            forms.append((form, helper))

    # Ensure our form comes first
    helper = FormHelper()
    helper.form_tag = False
    forms = [
        (NotificationSettingsForm(request.user, request.POST or None), helper),
    ] + forms

    if request.POST:
        if all(f.is_valid() for f, h in forms):
            for form, helper in forms:
                form.save()
            response = HttpResponseRedirect(reverse('sentry-account-settings-notifications') + '?success=1')
            return response

    context = csrf(request)
    context.update({
        'forms': forms,
        'page': 'notifications',
    })
    return render_to_response('sentry/account/notifications.html', context, request)
Exemple #9
0
class BorrarAgenciaForm(forms.Form):
    agencia_id = forms.IntegerField(widget=forms.widgets.HiddenInput, required=True)
    username = forms.CharField(required=True, label=_("Confirme su usuario"))
    password = forms.CharField(widget=forms.widgets.PasswordInput, required=True, label=_("Confirme su clave"))

    def __init__(self, *args, **kwargs):

        self.helper = FormHelper()
        self.helper.form_class = "uniForm"
        self.helper.form_method = "post"
        self.helper.form_action = "iamcast.views.borrar_agencia"
        self.helper.add_input(Submit("submit", _("Borrar Agencia")))

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

    def clean(self):
        cleaned_data = super(BorrarAgenciaForm, self).clean()
        agencia_id = cleaned_data.get("agencia_id")
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")

        if agencia_id and password:
            agencia = Agencia.objects.get(pk=agencia_id)
            if agencia.borrada():
                raise forms.ValidationError(ugettext(u"La agencia %s ya se encuentra borrada") % agencia.nombre)
            if agencia.user.username != username:
                raise forms.ValidationError(ugettext(u"El usuario ingresado es inválido"))
            if not check_password(password, agencia.user.password):
                raise forms.ValidationError(ugettext(u"El password ingresado es incorrescto"))

        return cleaned_data
def test_formset_with_helper_without_layout(settings):
    template = get_template_from_string(
        """
        {% load crispy_forms_tags %}
        {% crispy testFormSet formset_helper %}
    """
    )

    form_helper = FormHelper()
    form_helper.form_id = "thisFormsetRocks"
    form_helper.form_class = "formsets-that-rock"
    form_helper.form_method = "POST"
    form_helper.form_action = "simpleAction"

    TestFormSet = formset_factory(TestForm, extra=3)
    testFormSet = TestFormSet()

    c = Context({"testFormSet": testFormSet, "formset_helper": form_helper, "csrf_token": _get_new_csrf_key()})
    html = template.render(c)

    assert html.count("<form") == 1
    assert html.count("<input type='hidden' name='csrfmiddlewaretoken'") == 1

    # Check formset management form
    assert "form-TOTAL_FORMS" in html
    assert "form-INITIAL_FORMS" in html
    assert "form-MAX_NUM_FORMS" in html

    assert "formsets-that-rock" in html
    assert 'method="post"' in html
    assert 'id="thisFormsetRocks"' in html
    assert 'action="%s"' % reverse("simpleAction") in html
    if settings.CRISPY_TEMPLATE_PACK == "uni_form":
        assert 'class="uniForm' in html
Exemple #11
0
class EditForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(EditForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

        self.helper.form_method = 'post'
        self.helper.html5_required = True
        self.helper.layout = Layout(
            'name', 'date_of_birth', 'card_id', 'tel', 'address')
        self.helper.add_input(Submit('submit', 'Sửa lí lịch'))
        self.helper.add_input(Reset('reset', 'Reset'))

        self.fields['name'].error_message = Message.REQUIRED

    class Meta:
        model = CustomUser
        fields = {
            'name', 'address', 'card_id', 'tel', 'date_of_birth'
        }
        widgets = {
            'date_of_birth': forms.DateInput(
                attrs={'class': 'datepicker'}
            ),
        }
class ContactFormRus(forms.Form):
    """docstring for ContactFormRus"""

    def __init__(self, *args, **kwargs):
        # call original initializator
        super(ContactFormRus, self).__init__(*args, **kwargs)

        # this helper object allows us to us to customize form
        self.helper = FormHelper()

        # form tag attributes
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = reverse('contact_admin')

        # twitter bootstrap styles
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.label_class = 'col-sm-2 control label'
        self.helper.field_class = 'col-sm-10'

        # from buttons
        self.helper.add_input(Submit('send_button', u"Отправить"))

    from_email = forms.EmailField(label=u"Ваш емайл адресс")

    subject = forms.CharField(
        label=u"Заголовок",
        max_length=128)

    message = forms.CharField(
        label=u"Текст сообщения",
        widget=forms.Textarea)

    files = forms.FileField(required=False)
class ContactForm(forms.Form):

  def __init__(self, *args, **kwargs):
      # call original initializator
      super(ContactForm, self).__init__(*args, **kwargs)

      # this helper object allows us to customize form
      self.helper = FormHelper()

      # form tag attributes
      self.helper.form_class = 'form-horizontal'
      self.helper.form_method = 'post'
      self.helper.form_action = reverse('contact_admin')

      # twitter bootstrap styles
      self.helper.help_text_inline = True
      self.helper.html5_required = True
      self.helper.label_class = 'col-sm-2 control-label'
      self.helper.field_class = 'col-sm-10'

      # form buttons
      self.helper.add_input(Submit('send_button', u'Надіслати'))

  from_email = forms.EmailField(
      label=u"Ваша Емейл Адреса")
  subject = forms.CharField(
      label=u"Заголовок листа",
      max_length=128)
  message = forms.CharField(
      label=u"Текст повідомлення",
      widget=forms.Textarea)
Exemple #14
0
class ProviderForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProviderForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.fields["start_date"].help_text = "The date your company started."
        self.fields["tos"].help_text = \
            "A link to your terms of service that will be displayed at the bottom of each offer."

        self.helper.layout = Layout(
            Fieldset(
                'General',
                'name',
                'website',
                'start_date'
            ),
            Fieldset(
                'Legal',
                'tos',
                'aup',
                'sla',
                'billing_agreement'
            ),
            Fieldset(
                'Other',
                'logo'
            )
        )

        self.helper.add_input(Submit('save', 'Save Profile'))

    class Meta:
        model = Provider
        fields = ('name', 'start_date', 'website', 'tos', 'aup', 'sla', 'billing_agreement', 'logo')
Exemple #15
0
    def helper(self):
        helper = FormHelper()
        helper.form_tag = False

        helper.layout = Layout(
            Fieldset(
                _(u'You'),
                Div(Div(Field('name'), css_class="col-md-12"),
                    css_class="row"
                ),
                Div(Div(Field('email'), css_class="col-md-12"),
                    css_class="row"
                ),
            ),
            Fieldset(
                _(u'Your message'),



                Div(Div(PrependedText('subject', '[The Carib FOS]'), css_class="col-md-12"),
                    css_class="row"
                ),
                Div(Div(Field('message'), css_class="col-md-12"),
                css_class="row"
                ),
            ),
        )
        return helper
Exemple #16
0
class PageFour(forms.ModelForm):
    strenuous_activity_type = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_EXERCISE_TYPE)
    moderate_activity_type = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_EXERCISE_TYPE)
    strength_activity_type = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_EXERCISE_TYPE)
    strenuous_activity_days = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_DAYS)
    moderate_activity_days = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_DAYS)
    strength_activity_days = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_FOUR_CHOICE_SET_DAYS)

    def __init__(self, *args, **kwargs):
        super(PageFour, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.add_input(Submit('submit', 'Next Page'))
        self.helper.layout = Layout('',
                                InlineRadios('strenuous_activity_type'),
                                InlineRadios('moderate_activity_type'),
                                InlineRadios('strength_activity_type'),
                                InlineRadios('strenuous_activity_days'),
                                InlineRadios('moderate_activity_days'),
                                InlineRadios('strength_activity_days'),)

    class Meta:
        model = Survey
        fields = ('strenuous_activity_type', 'moderate_activity_type', 'strength_activity_type',
                    'strenuous_activity_days', 'moderate_activity_days', 'strength_activity_days',)
Exemple #17
0
class HostCreateForm(forms.ModelForm):
    """
    Quick Host creation form.
    """

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

        # Custom Crispiness
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-inline'
        self.helper.layout = Layout(
            Div('first_name', 'last_name'),
            Div('email'),
            Div('phone'),
            Div('address_1'),
            Div('address_2'),
        )
        self.helper.add_input(Submit('save', 'Save'))

    class Meta:
        model = models.Host
        fields = [
            'first_name',
            'last_name',
            'email',
            'phone',
            'address_1',
            'address_2',
        ]
class ConciergeUserAddExistingProductForm(forms.Form):
    input_formats = ['%Y-%m-%dT%H:%M']

    def __init__(self, *args, **kwargs):
        super(ConciergeUserAddExistingProductForm, self).__init__(*args, **kwargs)
        self.fields['provider'] = forms.ModelChoiceField(queryset=Provider.objects, widget=forms.Select(
            attrs={'data-url': reverse('engine_get_products_from_provider')}), required=True)
        self.fields['product'] = forms.IntegerField(widget=forms.Select(), required=True)
        self.fields['balance'] = forms.DecimalField(max_digits=19, decimal_places=3, required=True)
        self.fields['maturity_date'] = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), required=False,
                                                       help_text='Only for fixed term product')
        self.fields['rate'] = forms.DecimalField(max_digits=19, decimal_places=3, required=False,
                                                 help_text='Only for fixed term product')
        self.fields['term'] = forms.IntegerField(required=False, help_text='Only for fixed term product',
                                                 label='Term (months)')
        self.fields['fee_exempt'] = forms.BooleanField(initial=False, required=False,
                                                       help_text='Only for fixed term product')
        self.fields['user'] = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=User.objects, required=True)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal js-add-existing-products-form'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-10'
        self.helper.form_method = "POST"
        self.helper.form_action = reverse('engine_add_existing_product')
        self.helper.add_input(
            Button('Add Existing Product', 'Add Existing Product', css_class="btn btn-success js-add-existing-product",
                   data_url=reverse('engine_add_existing_product'))
        )
Exemple #19
0
class PageThree(forms.ModelForm):
    exercise_stay_health = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_lose_weight = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_improve_appearance = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_energize = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_sport = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_fun = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_muscle  = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    exercise_not = forms.ChoiceField(widget = forms.RadioSelect(), choices=PAGE_THREE_CHOICE_SET)
    
    def __init__(self, *args, **kwargs):
        super(PageThree, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.add_input(Submit('submit', 'Next Page'))
        self.helper.layout = Layout('',
                                    InlineRadios('exercise_stay_health'),
                                    InlineRadios('exercise_lose_weight'),
                                    InlineRadios('exercise_improve_appearance'),
                                    InlineRadios('exercise_energize'),
                                    InlineRadios('exercise_sport'),
                                    InlineRadios('exercise_fun'),
                                    InlineRadios('exercise_muscle'),
                                    InlineRadios('exercise_not'),)

    class Meta:
        model = Survey
        fields = ('exercise_stay_health', 'exercise_lose_weight', 'exercise_improve_appearance', 'exercise_energize',
                    'exercise_sport', 'exercise_fun', 'exercise_muscle', 'exercise_not',)
Exemple #20
0
class DateFilterForm(forms.Form):
    start = forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}, format='%d/%m/%Y'), input_formats=('%d/%m/%Y',))
    end = forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}, format='%d/%m/%Y'), input_formats=('%d/%m/%Y',))

    def __init__(self, user, *args, **kwargs):
        super(DateFilterForm, self).__init__(*args, **kwargs)
        self.user = user

        self.helper = FormHelper()
        self.helper.form_id = 'date-range-selector'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = '#'
        self.helper.add_input(Submit('submit', 'Filter'))

    def clean_start(self):
        start = self.cleaned_data['start']
        if not self.user.is_authenticated() and datetime.combine(start, time()) > (datetime.now() - timedelta(days=3)):
            raise forms.ValidationError("Last 72 hours are restricted.")

        return start


    def clean_end(self):
        end = self.cleaned_data['end']
        if not self.user.is_authenticated() and datetime.combine(end, time()) > (datetime.now() - timedelta(days=3)):
            raise forms.ValidationError("Last 72 hours are restricted.")

        return end
Exemple #21
0
class TransactionForm(ModelForm):
    class Meta:
        model = Transaction
        exclude = ('user',)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(TransactionForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'transaction-formId'
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = '.'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-7'
        self.helper.add_input(Submit('submit', 'Создать', css_class="col-lg-offset-2"))
        self.instance.user = user
        self.fields['account_from'] = forms.ModelChoiceField(queryset=Account.objects.filter(user=user), required=False,
                                                             label=_('Со счёта'))
        self.fields['account_to'] = forms.ModelChoiceField(queryset=Account.objects.filter(user=user), required=False,
                                                           label=_('На счёт'))
        self.fields['place'] = forms.ModelChoiceField(queryset=Place.objects.filter(user=user), required=False,
                                                      label=_('Место'))
        self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.filter(user=user), required=False,
                                                         label=_('Категория'))
def make_base_program_report_filter_form_helper():
    # lay out the filter form
    helper = FormHelper()
    helper.form_method = 'post'
    helper.form_action = reverse_lazy('reports')
    helper.layout = Layout(
        Fieldset(
            '',
            # 'Filter source records',
            Field('location'),
            Field('year'),
            Field('program'),
            FormActions(
                HTML(
                    '<button class="btn btn-warning form-submit" '
                    'data-dismiss="modal" aria-hidden="true"><i '
                    'class="icon-filter"></i> Filter</button>'
                ),
                HTML(
                    '<a class="btn form-reset" data-dismiss="modal" '
                    'aria-hidden="true">Reset</a>'
                ),
            )
        )
    )
    return helper
Exemple #23
0
class ContactForm(forms.Form):
    def __init__(self, *args, **kwargs):
        # call initializator
        super(ContactForm, self).__init__(*args, **kwargs)
        # helper customs form
        self.helper = FormHelper()

        # form tag attr
        self.helper.form_action = reverse("contact_admin")
        self.helper.form_method = "POST"
        self.helper.form_class = "form-horizontal"

        # twitter bootstrap styles
        self.helper.help_text_inline = True
        self.helper.html5required = True
        self.helper.label_class = "col-sm-3 control-label"
        self.helper.field_class = "col-sm-5"

        # buttons
        self.helper.add_input(Submit("send_button", _(u"Send")))

    from_email = forms.EmailField(label=_(u"Your email"))

    subject = forms.CharField(label=_(u"Title message"), max_length=128)

    message = forms.CharField(label=_(u"Your text"), max_length=2560, widget=forms.Textarea)
Exemple #24
0
class OutcomeStatusForm(OwnedModelForm):
    class Meta:
        model = Outcome
        fields = [
            'owner',
            'name',
            'status',
            'scope',
        ]

    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        self.owner = kwargs.pop('owner', None)
        super().__init__(*args, **kwargs)

        self.helper = FormHelper()
        outcome = self.instance
        self.helper.form_action = outcome.update_url + '?next={}'.format(request.path)
        self.helper.layout = Layout(
            Field('owner', type="hidden"),
            Field('name', type="hidden"),
            Field('scope', type="hidden"),
            Field('status', autofocus=True),
        )
        self.helper.add_input(Submit('update', _('Update')))
        self.helper.add_input(Submit('close', _('Close'), data_dismiss="modal", css_class='btn btn-secondary'))
Exemple #25
0
class StudentUpdateForm(ModelForm):

    class Meta:
        model = Student
        fields = {'first_name', 'last_name', 'middle_name', 'student_group', 'birthday', 'photo', 'ticket', 'notes'}

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

        self.helper = FormHelper(self)

        # set form tag attributes
        self.helper.form_action = reverse('students_edit',
            kwargs={'pk': kwargs['instance'].id})
        self.helper.form_method = 'POST'
        self.helper.form_class = 'form-horizontal'

        # set form field properties
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.label_class = 'col-sm-2 control-label'
        self.helper.field_class = 'col-sm-10'

        self.helper.add_input(Submit('submit', u'Зберегти'))
        self.helper.add_input(Submit('cancel_button', u'Скасувати', css_class='btn btn-link'))

        # add buttons
        self.helper.layout[-1] = Layout(FormActions())
Exemple #26
0
class CloseMeetingForm(forms.ModelForm):

    send_to_options = list(SendToOption.choices[2:])

    # On QA servers, allow users to prevent sending of protocols
    if settings.QA_SERVER:
        send_to_options.insert(0, SendToOption.choices[0])

    send_to = forms.TypedChoiceField(label=_("Send to"), coerce=int,
                                     choices=send_to_options,
                                     widget=forms.RadioSelect)

    class Meta:
        model = Meeting

        fields = (
                  'held_at',
                  )

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()

        self.helper.add_input(Submit('submit', _('Close Meeting')))

        super(CloseMeetingForm, self).__init__(*args, **kwargs)
Exemple #27
0
class UserProfileRegistrationForm(RegistrationFormUniqueEmail):
    website = forms.CharField(
        required=False)
        
    picture = forms.ImageField(
        required=False)
    
    def clean(self):
        cleaned_data = super(UserProfileRegistrationForm, self).clean()
        website = cleaned_data.get('website')

        #If URLS is not empty and doesn't starts with http://, prepend http://
        if website and not website.startswith('http://'):
            website = 'http://' + website
            cleaned_data['website'] = website

        return cleaned_data
    
    def __init__(self, *args, **kwargs):
        super(UserProfileRegistrationForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'registration_form'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-8'
        self.helper.form_method = 'post'
        self.helper.form_action = '.'
        
        self.helper.add_input(Submit('submit', 'Register'))
Exemple #28
0
class AgoraAdminForm(django_forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        super(AgoraAdminForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.request = request
        self.helper.layout = Layout(Fieldset(_('General settings'), 'pretty_name', 'short_description', 'biography', 'delegation_policy', 'is_vote_secret', 'membership_policy', 'comments_policy'))
        self.helper.add_input(Submit('submit', _('Save settings'), css_class='btn btn-success btn-large'))

    def clean_short_description(self):
        return clean_html(self.cleaned_data['short_description'])

    def clean_pretty_name(self):
        return clean_html(self.cleaned_data['pretty_name'], True)

    def clean_biography(self):
        return clean_html(self.cleaned_data['biography'])

    class Meta:
        model = Agora
        fields = ('pretty_name', 'short_description', 'is_vote_secret', 'delegation_policy',
            'biography', 'membership_policy', 'comments_policy')
        widgets = {
            'membership_policy': django_forms.RadioSelect,
            'comments_policy': django_forms.RadioSelect
        }
Exemple #29
0
class EventsForm(ModelForm):
    class Meta:
        model = NsaEvents
        fields='__all__'
    def __init__(self, *args, **kwargs):
        super(EventsForm,self).__init__(*args, **kwargs)
        self.fields['eventLeader'].queryset = User.objects.filter(Q(groups__name='AVC')|Q(groups__name='VolunteerManager'))
        self.fields['daysOfWeek'].widget = forms.CheckboxSelectMultiple()
        self.helper = FormHelper(self)
        self.helper.form_class='form-horizontal'
        self.helper.form_class='volunteerProfile'
        self.helper.form_id='volunteerProfileForm'
        #self.helper.label_class='col-md-2'
        #self.helper.field_class='col-md-5'
        self.helper.layout = Layout(
        'eventName',
        Field('eventDate', css_class='datepicker',placeholder='Select Date'),
        'eventLeader',
        'location',
        'autoApprove',
        'description',
        'internalComments',
        'recurring',
        'daysOfWeek',
        'allowView',
        HTML('<div class="form-group"><div class="col-lg-5"></div>'),
        ButtonHolder(
        self.helper.add_input(Submit('save', 'Save', css_class="btn btnnavy")),
        self.helper.add_input(Submit('saveAndAdd', 'Save & Add Another', css_class="btn btnnavy")),
        self.helper.add_input(Button('cancel', 'Cancel', css_class='btn-default', onclick="window.history.back()"))
        ))
def make_site_filter_form_helper():
    helper = FormHelper()
    helper.form_action = reverse_lazy('sites')
    helper.form_class = 'form-horizontal'
    helper.form_method = 'post'
    helper.layout = Layout(
        Fieldset(
            '',
            # 'Filter displayed sites',
            Field('location'),
            FormActions(
                HTML(
                    '<button class="btn btn-warning form-submit" '
                    'data-dismiss="modal" aria-hidden="true">'
                    '<i class="icon-filter"></i> Filter</button>'
                ),
                HTML(
                    '<a class="btn form-reset" data-dismiss="modal" '
                    'aria-hidden="true">Reset</a>'
                ),
            )
        )
    )

    return helper
Exemple #31
0
 def __init__(self, *args, **kwargs):
     super(AdmissionForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_method = 'post'
     self.helper.add_input(Submit('submit', 'Submit'))
Exemple #32
0
 def __init__(self, *args, **kwargs):
     super(EmailForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_tag = False
Exemple #33
0
    def __init__(self, *args, **kwargs):
        super(AnswerForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.add_layout(InlineRadios("score"))
Exemple #34
0
 def __init__(self, *args, **kwargs):
     super(PlaceFormCreate, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_tag = False
Exemple #35
0
    def __init__(self, survey, *args, **kwargs):
        self.title = survey.public_title
        self.desc = survey.public_description
        super(SurveyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.label_class = "col-m2-2 font-weight-bold"

        for question in survey.questions:
            if question.published:
                choices_checkbox = ()
                choices_radio = ()
                add_text_field_id = -1
                for answer in question.answers:
                    if answer.published:
                        if answer.answer_type == 'checkbox':
                            choices_checkbox = (*choices_checkbox,
                                                (str(answer.id),
                                                 answer.public_description))
                            if answer.private_description == 'input':
                                add_text_field_id = answer.id
                        if answer.answer_type == 'radio':
                            choices_radio = (*choices_radio,
                                             (str(answer.id),
                                              answer.public_description))
                            if answer.private_description == 'input':
                                add_text_field_id = answer.id

                        if answer.answer_type == 'input':
                            self.fields[str(answer.id)] = forms.CharField(
                                label=question.question_text,
                                strip=True,
                                required=False)
                        if answer.answer_type == 'textarea':
                            self.fields[str(answer.id)] = forms.CharField(
                                label=question.question_text,
                                widget=forms.Textarea,
                                strip=True,
                                required=False)

                if len(choices_checkbox) > 0:
                    self.fields[str(question.id) +
                                '_checkbox'] = forms.MultipleChoiceField(
                                    label=question.question_text,
                                    choices=choices_checkbox,
                                    widget=forms.CheckboxSelectMultiple,
                                    required=False)
                if len(choices_radio) > 0:
                    self.fields[str(question.id) +
                                '_radio'] = forms.ChoiceField(
                                    label=question.question_text,
                                    choices=choices_radio,
                                    widget=forms.RadioSelect,
                                    required=False)
                if add_text_field_id > -1:
                    self.fields[str(add_text_field_id) +
                                '_checkboxinput'] = forms.CharField(
                                    widget=forms.TextInput(
                                        attrs={'class': 'form-control-sm'}),
                                    strip=True,
                                    required=False,
                                    label='')
Exemple #36
0
class TalkForm(forms.ModelForm):
    talk_type = TalkCategorisationField(model=TalkType)
    track = TalkCategorisationField(model=Track)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        initial = kwargs.setdefault('initial', {})
        if kwargs['instance']:
            authors = kwargs['instance'].authors.all()
        else:
            authors = initial['authors'] = [self.user]

        if not (settings.WAFER_PUBLIC_ATTENDEE_LIST
                or self.user.has_perm('talks.change_talk')):
            # copy base_fields because it's a shared class attribute
            self.base_fields = copy.deepcopy(self.base_fields)
            self.base_fields['authors'].limit_choices_to = {
                'id__in': [author.id for author in authors]
            }

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

        if not self.user.has_perm('talks.edit_private_notes'):
            self.fields.pop('private_notes')

        if not Track.objects.exists():
            self.fields.pop('track')

        if not TalkType.objects.exists():
            self.fields.pop('talk_type')
        else:
            self.fields['talk_type'] = TalkCategorisationField(
                model=TalkType, initial=self.initial.get('talk_type'))

        if not settings.WAFER_VIDEO:
            self.fields.pop('video')
        if not settings.WAFER_VIDEO_REVIEWER:
            self.fields.pop('video_reviewer')

        # We add the name, if known, to the authors list
        self.fields['authors'].label_from_instance = render_author

        self.helper = FormHelper(self)
        submit_button = Submit('submit', _('Submit'))
        instance = kwargs['instance']
        if instance:
            self.helper.layout.append(
                FormActions(
                    submit_button,
                    HTML('<a href="%s" class="btn btn-danger">%s</a>' %
                         (reverse('wafer_talk_withdraw',
                                  args=(instance.pk, )), _('Withdraw Talk')))))
        else:
            self.helper.add_input(submit_button)

    def clean_video_reviewer(self):
        video = self.cleaned_data['video']
        reviewer = self.cleaned_data['video_reviewer']
        if video and not reviewer:
            raise forms.ValidationError(
                _('A reviewer is required, if video is permitted.'))
        return reviewer

    class Meta:
        model = Talk
        fields = ('title', 'talk_type', 'track', 'abstract', 'authors',
                  'video', 'video_reviewer', 'notes', 'private_notes')
        widgets = {
            'abstract': MarkItUpWidget(),
            'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}),
            'authors': Select2Multiple(),
        }
Exemple #37
0
 def __init__(self, *args, **kwargs):
     super(WarrantyCardItemFormSet, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_tag = False
     self.helper.form_class = 'form-inline'
     self.helper.field_template = 'bootstrap3/layout/inline_field.html'
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_method = 'post'
     self.helper.add_input(Submit('submit', 'Save issu'))
Exemple #39
0
    def __init__(self, *args, **kwargs):
        super(MinstrelForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                'Melody Tables',
                DynamicFields('Dynamic', 'melody_dynamics', 16),
                ProgressionTitle('I', 'II', 'III', 'IV', 'V', 'VI', 'VII'),
                ProgressionFields('I', 'melody_harmonic_compilance_I', 7),
                ProgressionFields('II', 'melody_harmonic_compilance_II', 7),
                ProgressionFields('III', 'melody_harmonic_compilance_III', 7),
                ProgressionFields('IV', 'melody_harmonic_compilance_IV', 7),
                ProgressionFields('V', 'melody_harmonic_compilance_V', 7),
                ProgressionFields('VI', 'melody_harmonic_compilance_VI', 7),
                css_class='col-sm-6',
            ),
            Fieldset(
                'Harmony',
                'key',
                ProgressionTitle('I', 'II', 'III', 'IV', 'V', 'VI'),
                ProgressionFields('I', 'harmony_markov_chain_I', 6),
                ProgressionFields('II', 'harmony_markov_chain_II', 6),
                ProgressionFields('III', 'harmony_markov_chain_III', 6),
                ProgressionFields('IV', 'harmony_markov_chain_IV', 6),
                ProgressionFields('V', 'harmony_markov_chain_V', 6),
                ProgressionFields('VI', 'harmony_markov_chain_VI', 6),
                css_class='col-sm-6',
            ),
            Fieldset(
                'Tempo',
                'tempo_fixed',
                'tempo_lower',
                'tempo_upper',
                css_class='col-sm-6',
            ),
            Fieldset(
                'Instruments',
                'instruments_melody',
                'instruments_chord',
                'instruments_bass',
                css_class='col-sm-6',
            ),
            Fieldset(
                'Melody Params',
                Div(
                    'melody_power',
                    'melody_preferred_center',
                    'melody_preferred_lower',
                    'melody_preferred_upper',
                    css_class='col-sm-6',
                ),
                Div(
                    'melody_maximum_lower',
                    'melody_maximum_upper',
                    'melody_inner_drop_off',
                    'melody_outer_drop_off',
                    css_class='col-sm-6',
                ),
                css_class='col-sm-12 whole',
            ),
            FormActions(
                Submit('play', "Play", css_class="btn btn-success"),
                Submit('random', 'Random', css_class="btn btn-info"),
                Submit('happy', 'Happy', css_class="btn btn-success"),
                Submit('angry', 'Angry', css_class="btn btn-danger"),
                Submit('sad', 'Sad', css_class="btn btn-primary"),
                Submit('tender', 'Tender', css_class="btn btn-warning"),
                css_class='col-sm-12',
            ),
        )
Exemple #40
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper(self)
Exemple #41
0
 def __init__(self, *args, **kwargs):
     super(TicketForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.add_input(Submit('submit', _('Claim')))
Exemple #42
0
 def __init__(self, *args, **kwargs):
     super(ContactForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_show_labels = False
Exemple #43
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_tag = False
     self.helper.layout = Layout(Field("name", type='hidden'))
class CreateQuizForm(forms.Form):

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

		self.fields['Quiz Title'] = forms.CharField(max_length=50, required=False)
		self.fields['Quiz Description'] = forms.CharField(widget=forms.Textarea, required=False)
		self.fields['Number of Questions'] = forms.IntegerField(required=False)
		self.fields['Pass Mark'] = forms.IntegerField(max_value=100, required=False)
		self.fields['Upload Quiz Posts and Labels'] = forms.FileField()
	        #self.fields['Posts'] = forms.ModelMultipleChoiceField(queryset=Post.objects.all())

        	#self.fields['Posts'].queryset = Post.objects.filter(content='post1')
		#posts = forms.ModelMultipleChoiceField(queryset=Post.objects.all(),
#                    widget=FilteredSelectMultiple('Post', False),
 #                   required=False)

		#self.fields['Participating Coders'] = forms.CharField(widget=forms.Textarea, required=False)

		self.helper = FormHelper()
		self.helper.form_id = 'create_quiz_form'
		self.helper.form_method = 'POST'
		self.helper.form_action = '/quiz/create_quiz/'
		self.helper.layout = Layout(
			
			HTML("""<div class="panel panel-info">
					<div class="panel-heading">
						Create Quiz 
					</div>
					<div class="panel-body">					
					"""),
			Field('Quiz Title', placeholder="Enter the quiz title..."),
			Field('Quiz Description', placeholder="Write some description about the quiz..."),
			Field('Number of Questions', placeholder="Minimum number of questions to be responded by labelers for this quiz"),
			Field('Pass Mark', placeholder="Minimum score to be passed for this quiz"),
			Field('Upload Quiz Posts and Labels'),
			HTML("""<style> p.solid {border : 1px; display: inline-block ; border-style: solid;} </style>
<!--table style="border: 1px solid black;"--> 

<tr>
<td>
<p class="solid">
<b>Note</b> : Upload a csv file with <a href="/media/sample_quiz.csv" download="sample_quiz.csv">this sample format</a> <br/>[All labels separated with pipelines on the first line.<br/> Each post and its corresponding label on a separate line after that.]
</td> 
</tr>
</p>
<!--/table-->
"""),

			#Field('Posts'),
			HTML("""</div>
					</div>"""),			
			)
		self.helper.add_input(Submit('create_quiz_submit', 'Save', css_class='btn btn-info btn-sm pull-right'))



	def create_quiz(self, quiz_title, quiz_description, max_posts, pass_mark, quiz_upload_file, user):
		try:
			quiz_object = Quiz.objects.create(
				title = quiz_title,
				description = quiz_description,
				max_posts = max_posts,
				pass_mark = pass_mark,
				creator = user, )
#				upload_quiz = quiz_upload_file)

			#csvfile = open(str(quiz_upload_file), 'rb')# as csvfile:
			#print (csvfile)
			#readerR = csv.reader(csvfile, delimiter='|', skipinitialspace=True)
			readerR = csv.reader(TextIOWrapper(quiz_upload_file), delimiter='|', skipinitialspace=True)
			print (readerR)
#                       readerF = csv.reader(TextIOWrapper(task_upload_file), delimiter='|', skipinitialspace=True)
			#reader = csv.reader(open(task_upload_file, newline=''), delimiter='|')
			#print (readerF)
			
			#reader = csv.reader(TextIOWrapper(quiz_upload_file), delimiter='|', skipinitialspace=True)
#			print ('here in quiz parts')

			answer_key_object = AnswerKey.objects.create(quiz=quiz_object)
			print (answer_key_object)
			label_list = []
			labels = next(readerR)
#			print ('here in quiz parts')
			print (labels)
			for label in labels:
				label_object = Label.objects.create(content=label)
				label_list.append(label_object)
				quiz_object.label_list.add(label_object)

			posts = readerR
			for post in posts:
				post_object = Post.objects.create(
					content = post[0],
					author = user)
				quiz_object.post_list.add(post_object)
				answer_object = Answer.objects.create(
					answer_key = answer_key_object,
					post = post_object,
					label = [item for item in label_list if item.content == post[1]][0])
		except:
			return None

		return quiz_object

	

	def add_participant(self, task, coder):
		Participation.objects.create(
			task=task,
			coder=coder)

	def save_quiz(self, task):
		#participating_coders = self.cleaned_data['Participating Coders']
		#coder_list = participating_coders.split()
		#for coder in coder_list:
		#	subject = str.format("Task created for {0}", coder)
		#	message = str.format("Hi {0},\n\n\tYou have been selected to complete a task. Please start here: [WEBSITE_URL]\n\nBest,\nUCIPT Team", coder)
			send_mail(subject, message, '*****@*****.**', coder_list, fail_silently=False)
			self.add_participant(task, coder)
 def __init__(self, *args, **kwargs):
     super(EstrategiaObjetivoForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('objetivo', css_class='input-xlarge'),
     )  
    def __init__(self, issuer_pk=None, user=None, *args, **kwargs):
        """Initiate the class."""

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

        # Load data from models
        issuer_obj = Issuer.objects.get(pk=issuer_pk)
        onboarding_obj = OnboardingProcess.objects.get(issuer=issuer_obj)

        self.helper = FormHelper(form=self)
        self.helper.layout = Layout()
        self.helper.layout.append(
            Field(
                'issuer_pk',
                type='hidden',
                value=issuer_pk,
            ),
        )

        if has_group(user, 'Commercial'):

            # These fields are not required here
            self.fields['primary_analyst'].required = False
            self.fields['secondary_analyst'].required = False

            _relationship_manager = Field('relationship_manager')
            _issuer_type = Field('issuer_type')
            _requested_rating = Field('requested_rating')
            _target_delivery_date = Field('target_delivery_date')
            _engagement_letter_signed = Field('engagement_letter_signed')

            # Set default values of the choice field form
            requested_ratings_list = []
            if onboarding_obj.issuer_long_term:
                requested_ratings_list.append('lt_rating')

            if onboarding_obj.issuer_short_term:
                requested_ratings_list.append('st_rating')

            if onboarding_obj.instrument_rating:
                requested_ratings_list.append('instrument_rating')

            if onboarding_obj.target_delivery_date:
                self.fields['target_delivery_date'].initial = \
                    onboarding_obj.target_delivery_date

            self.fields["requested_rating"].initial = (requested_ratings_list)

        else:

            # Make sure the view doesn't overwrite with null
            self.helper.layout.append(
                Field(
                    'relationship_manager',
                    type='hidden',
                    value=issuer_obj.relationship_manager,
                ),
            )

            self.helper.layout.append(
                Field(
                    'issuer_type',
                    type='hidden',
                    value=issuer_obj.issuer_type,
                ),
            )

            # We don't need to pass these values when saving as a CRO
            self.fields['engagement_letter_signed'].required = False
            self.fields['requested_rating'].required = False

            _relationship_manager = Div(
                Div(HTML('Relationship manager:')),
                Div(HTML('{}'.format(
                    issuer_obj.relationship_manager.get_full_name()))),
                Div(HTML('&nbsp;'))
            )

            if issuer_obj.issuer_type.id == 1:
                issuer_type = 'Corporates'
            elif issuer_obj.issuer_type.id == 2:
                issuer_type = 'Financial institutions'
            elif issuer_obj.issuer_type.id == 3:
                issuer_type = 'Corporates, real estate'

            _issuer_type = Div(
                Div(HTML('Methodology:')),
                Div(HTML('{}'.format(issuer_type))),
                Div(HTML('&nbsp;'))
            )

            requested_ratings = ''

            if onboarding_obj.issuer_long_term:
                requested_ratings += 'Issuer long-term'

            if onboarding_obj.issuer_short_term:
                requested_ratings += ', Issuer short-term'

            if onboarding_obj.instrument_rating:
                requested_ratings += ', Instrument'

            _requested_rating = Div(
                Div(HTML('Requested rating:')),
                Div(HTML('{}'.format(requested_ratings))),
                Div(HTML('&nbsp;'))
            )

            if onboarding_obj.target_delivery_date is not None:
                _target_delivery_date = Div(
                    Div(HTML('Target delivery date:')),
                    Div(HTML('{}'.format(
                        onboarding_obj.target_delivery_date.strftime(
                            '%Y-%m-%d')))),
                    Div(HTML('&nbsp;'))
                )

            else:
                _target_delivery_date = HTML('A target delivery date has '
                                             'not been specified.')

            _engagement_letter_signed = HTML('The engagement letter has '
                                             'been signed.')

            self.helper.layout.append(
                Div(
                    Div(
                        Field('primary_analyst'),
                        css_class='col-md-12'),
                    css_class='row',
                ),
            )
            self.helper.layout.append(
                Div(
                    Div(
                        Field('secondary_analyst'),
                        css_class='col-md-12'),
                    css_class='row',
                ),
            )

        self.helper.layout.append(
            Div(
                Div(
                    _relationship_manager,
                    css_class='col-md-12',
                ),
                css_class='row',
            ),
        )
        self.helper.layout.append(
            Div(
                Div(
                    _issuer_type,
                    css_class='col-md-12'),
                css_class='row',
            ),
        )
        self.helper.layout.append(
            Div(
                Div(
                    _requested_rating,
                    css_class='col-md-12'),
                css_class='row',
            ),
        )
        self.helper.layout.append(
            Div(
                Div(
                    _target_delivery_date,
                    css_class='col-md-12'),
                css_class='row',
            ),
        )
        self.helper.layout.append(
            Div(
                Div(
                    _engagement_letter_signed,
                    css_class='col-md-12'),
                css_class='row',
            ),
        )
 def __init__(self, *args, **kwargs):
     super(EstrategiaProblematicaForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('problematica', css_class='input-xlarge'),
     )  
class confForm(forms.ModelForm):
    helper = FormHelper()

    helper.layout = Layout(
        Fieldset(

            'Name and acronym',
            HTML('<i>Enter the conference full name</i>'),
            'conference_name',
            HTML('<p><i>Enter the conference acronym</i></p>'),
            'conference_acronym',

        ),
        HTML('<hr>'),

        Fieldset(
            'Conference information',
            HTML('<p><i></i></p>'),
            'conference_webpage',
            HTML('<p><i></i></p>'),
            'conference_venue',
            HTML('<p><i></i></p>'),
            'conference_country',
            HTML('<p><i></i></p>'),
            'conference_city',
        ),
        HTML('<hr>'),

        Fieldset(
            'Date',
            HTML('<p><i></i></p>'),
            'conference_start',
            HTML('<p><i></i></p>'),
            'conference_end',
        ),
        HTML('<hr>'),

        Fieldset(
            'Research Area',
            HTML('<p><i></i></p>'),
            'conference_research_area',
            HTML('<p><i></i></p>'),
            'conference_area_notes',
        ),
        HTML('<hr>'),

        Fieldset(
            'Organizer',
            HTML('<p><i></i></p>'),
            'conference_organizer',
            HTML('<p><i></i></p>'),
            'conference_organizer_webpage',
            HTML('<p><i></i></p>'),
            'conference_organizer_contact',
        ),
        HTML('<hr>'),

        Fieldset(
            'Other information',
            HTML('<p><i></i></p>'),
            'conference_other_info',

        ),
        FormActions(
            Submit('send_installation', 'Send Installation'),

        )

    )
    helper.form_method = 'POST'
    helper.form_class = 'form-horizontal'

    class Meta:
        model = conference_form
        fields = [
            'conference_name',
            'conference_acronym',
            'conference_webpage',
            'conference_venue',
            'conference_country',
            'conference_city',
            'conference_start',
            'conference_end',
            'conference_organizer',
            'conference_organizer_contact',
            'conference_organizer_webpage',
            'conference_area_notes',
            'conference_other_info',
            'conference_research_area',


        ]
 def __init__(self, *args, **kwargs):
     super(EstrategiaFactoresHabilitantesForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('factoreshabilitantes', css_class='input-xlarge'),
     )  
 def __init__(self, *args, **kwargs):
     super(EstrategiaSolucionPoliticaForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('solucionpolitica', css_class='input-xlarge'),
     )  
 def __init__(self, *args, **kwargs):
     super(EstrategiaResultadosIntermediosForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('resultadosintermedios', css_class='input-xlarge'),
     )  
 def __init__(self, *args, **kwargs):
     super(EstrategiaActoresRelevantesForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('actoresrelevantes', css_class='input-xlarge'),
     )
Exemple #53
0
class ProjectAdvancedForm(ProjectTriggerBuildMixin, ProjectForm):
    """Advanced project option form."""
    class Meta:
        model = Project
        per_project_settings = (
            'default_version',
            'default_branch',
            'privacy_level',
            'analytics_code',
            'show_version_warning',
            'single_version',
        )
        # These that can be set per-version using a config file.
        per_version_settings = (
            'documentation_type',
            'requirements_file',
            'python_interpreter',
            'install_project',
            'use_system_packages',
            'conf_py_file',
            'enable_pdf_build',
            'enable_epub_build',
        )
        fields = (
            *per_project_settings,
            *per_version_settings,
        )

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

        self.helper = FormHelper()
        help_text = render_to_string(
            'projects/project_advanced_settings_helptext.html')
        self.helper.layout = Layout(
            Fieldset(
                _("Global settings"),
                *self.Meta.per_project_settings,
            ),
            Fieldset(
                _("Default settings"),
                HTML(help_text),
                *self.Meta.per_version_settings,
            ),
        )
        self.helper.add_input(Submit('save', _('Save')))

        default_choice = (None, '-' * 9)
        # commit_name is used as the id because it handles
        # the special cases of LATEST and STABLE.
        all_versions_choices = [(v.commit_name, v.verbose_name)
                                for v in self.instance.versions.all()]
        self.fields['default_branch'].widget = forms.Select(
            choices=[default_choice] + all_versions_choices, )

        active_versions = self.get_all_active_versions()

        if active_versions:
            self.fields['default_version'].widget = forms.Select(
                choices=active_versions, )
        else:
            self.fields['default_version'].widget.attrs['readonly'] = True

    def clean_conf_py_file(self):
        filename = self.cleaned_data.get('conf_py_file', '').strip()
        if filename and 'conf.py' not in filename:
            raise forms.ValidationError(
                _(
                    'Your configuration file is invalid, make sure it contains '
                    'conf.py in it.',
                ),
            )  # yapf: disable
        return filename

    def get_all_active_versions(self):
        """
        Returns all active versions.

        Returns a smartly sorted list of tuples.
        First item of each tuple is the version's slug,
        and the second item is version's verbose_name.
        """
        version_qs = self.instance.all_active_versions()
        if version_qs.exists():
            version_qs = sort_version_aware(version_qs)
            all_versions = [(version.slug, version.verbose_name)
                            for version in version_qs]
            return all_versions
        return None
 def __init__(self, *args, **kwargs):
     super(EstrategiaBarrerasForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper() 
     self.helper.layout = Layout(
                             Field('barreras', css_class='input-xlarge'),
     )  
Exemple #55
0
class AlloggioForm(TranslationModelForm):

    helper = FormHelper()
    helper.form_tag = False
    helper.disable_csrf = True
    helper.form_method = 'POST'

    helperTop = FormHelper()
    helperTop.form_tag = False
    helperTop.disable_csrf = True
    helperTop.form_method = 'POST'

    helperTop.layout = Layout(
        Div(Field('descrizione_breve',
                  css_class='input-lg',
                  wrapper_class='col-md-12'),
            Field('descrizione_lunga',
                  css_class='input-lg',
                  wrapper_class='col-md-12'),
            Field('regole_casa',
                  css_class='input-lg',
                  wrapper_class='col-md-12'),
            css_class='row'),
        Div(
            Field('tipo', css_class='input-lg', wrapper_class='col-md-6'),
            Field('piano', css_class='input-lg', wrapper_class='col-md-4'),
            # Field('ascensore', css_class='input-lg', wrapper_class='col-md-2'),
            Div(InlineField('ascensore'),
                InlineField('accesso_disabili'),
                InlineField('animali_ammessi'),
                css_class='col-md-2'),
            Field('postiletto', css_class='input-lg',
                  wrapper_class='col-md-3'),
            Field('descrizione_letti',
                  css_class='input-lg',
                  wrapper_class='col-md-9'),
            css_class='row'),
    )

    helper.layout = Layout(

        # Fieldset('Descrizione e regole',
        #     Div(
        #         Field('descrizione_breve', css_class='input-lg', wrapper_class='col-md-12'),
        #         Field('descrizione_lunga', css_class='input-lg', wrapper_class='col-md-12'),
        #         Field('regole_casa', css_class='input-lg', wrapper_class='col-md-12'),
        #         css_class='row'
        #     ),
        #     css_class='col-md-12'
        #  ),
        #
        #
        # Fieldset('Lavoro',
        #
        #          Div(
        # Field('tipo', css_class='input-lg',wrapper_class='col-md-6'),
        # Field('piano', css_class='input-lg', wrapper_class='col-md-4'),
        # Field('postiletto', css_class='input-lg', wrapper_class='col-md-6'),
        # Field('descrizione_letti', css_class='input-lg',wrapper_class='col-md-12'),
        #             css_class='row'
        #         ),
        #          css_class='col-md-12'
        # ),
        Fieldset(
            'Varie',
            Div(
                Field('prezzo', css_class='input-lg',
                      wrapper_class='col-md-3'),
                Field('prezzo_week',
                      css_class='input-lg',
                      wrapper_class='col-md-3'),
                Field('iva', css_class='input-lg', wrapper_class='col-md-3'),
                # Div(
                #     'ascensore',
                #     'accesso_disabili',
                #     'animali_ammessi',
                #     # 'ascensore',
                #     css_class='col-md-4'
                # ),

                # Field('ascensore', css_class='input-lg', wrapper_class='col-md-4'),
                # Field('accesso_disabili', css_class='input-lg', wrapper_class='col-md-4'),
                # Field('animali_ammessi', css_class='input-lg', wrapper_class='col-md-4'),
                Field('posti_auto',
                      css_class='input-lg',
                      wrapper_class='col-md-3'),
                Div(InlineCheckboxes('servizi_base'), css_class='col-md-4'),
                # Div(
                #     InlineCheckboxes('servizi_opzionali'),
                #     css_class='col-md-4'
                # ),
                css_class='row'),
            css_class='col-md-12'),

        # piano = models.IntegerField(default=0)
        # ascensore = models.BooleanField(default=False)
        # accesso_disabili = models.BooleanField(default=False)
        # animali_ammessi = models.BooleanField(default=False)
        # posti_auto = models.IntegerField(default=0)

        #
        # Div(
        #     InlineCheckboxes('teach_level',wrapper_class='col-md-12'),
        #     css_class='col-md-12'
        # ),
        #
        # # PrependedAppendedText('price', '$', '.00' ),
        # HTML('<div class="col-md-12" id="tagManager"></div>'),
        # HTML('<div class="col-md-12" ><hr></div>'),
    )

    class Meta:
        from django.forms import TextInput, Textarea
        model = Alloggio
        exclude = ('owner', 'address', 'calendar', 'letti')

        widgets = {
            'descrizione_breve':
            TextInput(),
            'descrizione_lunga':
            Textarea(attrs={
                'cols': 80,
                'rows': 5,
                'style': "resize:none"
            }),
            'regole_casa':
            Textarea(attrs={
                'cols': 80,
                'rows': 3,
                'style': "resize:none"
            }),
        }

        # widgets = {
        #     'servizi_base':  forms.ModelMultipleChoiceField()
        # }

    def __init__(self, *args, **kw):
        # initial=
        super(AlloggioForm, self).__init__(*args, **kw)

        for f in self._meta.model._meta.fields:
            print f, isinstance(f, TranslationField)
Exemple #56
0
class BaseMandatForm(forms.ModelForm):
    default_date_range = None

    membre_reseau_elus = forms.ChoiceField(
        label="Souhaitez-vous faire partie du réseau des élu⋅es ?",
        choices=(
            (Person.MEMBRE_RESEAU_SOUHAITE, "Oui"),
            (Person.MEMBRE_RESEAU_NON, "Non"),
        ),
        required=True,
    )

    dates = DateRangeField(
        label="Dates de votre mandat",
        required=True,
        help_text=
        "Indiquez la date de votre entrée au conseil, et la date approximative à laquelle votre"
        " mandat devrait se finir (à moins que vous n'ayiez déjà démissionné).",
    )

    delegations = forms.MultipleChoiceField(
        label=
        "Si vous êtes vice-président⋅e, indiquez dans quels domains rentrent vos"
        " délégations.",
        choices=DELEGATIONS_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        required=False,
    )

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

        self.instance.person = person

        self.fields["mandat"].choices = [
            (None, "Indiquez votre situation au conseil")
        ] + self.fields["mandat"].choices[1:]

        if person.membre_reseau_elus == Person.MEMBRE_RESEAU_NON:
            self.fields[
                "membre_reseau_elus"].initial = Person.MEMBRE_RESEAU_NON
        elif person.membre_reseau_elus != Person.MEMBRE_RESEAU_INCONNU:
            del self.fields["membre_reseau_elus"]

        self.fields["dates"].initial = self.default_date_range

        self.helper = FormHelper()
        self.helper.add_input(Submit("valider", "Valider"))
        self.helper.layout = Layout("mandat", "dates", "delegations")
        if "membre_reseau_elus" in self.fields:
            self.helper.layout.fields.insert(0, "membre_reseau_elus")

    def save(self, commit=True):
        if self.instance.statut in [
                StatutMandat.CONTACT_NECESSAIRE,
                StatutMandat.IMPORT_AUTOMATIQUE,
        ]:
            self.instance.statut = StatutMandat.INSCRIPTION_VIA_PROFIL

        if "membre_reseau_elus" in self.fields:
            self.instance.person.membre_reseau_elus = self.cleaned_data[
                "membre_reseau_elus"]
            self.instance.person.save(update_fields=["membre_reseau_elus"])

        return super().save(commit=commit)

    class Meta:
        fields = ("dates", "mandat")
        error_messages = {
            NON_FIELD_ERRORS: {
                "dates_overlap":
                "Vous avez déjà indiqué un autre mandat pour ce conseil à des dates qui se"
                " chevauchent. Modifiez plutôt cet autre mandat."
            }
        }
Exemple #57
0
    def __init__(self, *args, **kwargs):
        init_phone = ""
        init_email = ""
        init_tenant = ""
        init_region = ""
        selected_region = ""
        next_url = None
        origin = None
        prefix_url = ""
        if len(kwargs) > 0:
            if kwargs.get("initial") is not None:
                initalObj = kwargs.get("initial")
                init_phone = initalObj["phone"]
                init_email = initalObj["email"]
                init_tenant = initalObj["tenant"]
                init_region = initalObj["region"]
            if kwargs.get("region_level") is not None:
                selected_region = kwargs["region_level"]["region"]
                kwargs.pop("region_level")
            if kwargs.get("next_url") is not None:
                next_url = kwargs["next_url"]
                prefix_url += "&next={0}".format(next_url)
                kwargs.pop("next_url")
            if kwargs.get("origin") is not None:
                origin = kwargs["origin"]
                prefix_url += "&origin={0}".format(origin)
                kwargs.pop("origin")
        if len(prefix_url) > 1:
            prefix_url = "?" + prefix_url[1:]
        if len(args) > 0:
            if type(args) is tuple:
                if args[0].get("initial") is not None:
                    initalObj = args[0]["initial"]
                    if type(initalObj) is list:
                        initalObj = initalObj(0)
                    init_phone = initalObj["phone"]
                    init_email = initalObj["email"]
                    init_tenant = initalObj["tenant"]
                    init_region = initalObj["region"]
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False

        text_phone = "手机号"
        text_email = "请输入邮箱地址"
        text_tenant = "团队域名"
        if init_phone is not None and init_phone != "":
            self.fields['phone'].widget.attrs['readonly'] = True
            text_phone = init_phone
        if init_email is not None and init_email != "":
            self.fields['email'].widget.attrs['readonly'] = True
            text_email = init_email
        if init_tenant is not None and init_tenant != "":
            self.fields['tenant'].widget.attrs['readonly'] = True
            text_tenant = init_tenant
        if init_region is not None and init_region != "":
            self.fields['machine_region'].initial = init_region
            self.fields['machine_region'].widget.attrs['readonly'] = True
        if selected_region is not None and selected_region != "":
            self.fields['machine_region'].initial = selected_region

        init_region = RegionInfo.register_choices()[0][0]
        # 对于社区版注册表单进行处理
        is_private = sn.instance.is_private()
        tenant_name = None
        if is_private:
            tenant_num = Tenants.objects.count()
            if tenant_num == 1:
                tenant_list = Tenants.objects.all()
                tenant = tenant_list[0]
                tenant_name = tenant.tenant_name

        # if settings.MODULES["Sms_Check"]:
        if settings.MODULES["WeChat_Module"]:
            self.helper.layout = Layout(
                Div(
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control") if tenant_name is None else
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control",
                          readonly="readonly",
                          value=tenant_name),
                    Field('nick_name',
                          css_class="form-control",
                          placeholder='请输入用户名(可使用小写英文字母、数字、下划线及中划线)'),
                    Field('email',
                          css_class="form-control",
                          placeholder='请输入邮箱(选填)'),
                    HTML("<hr/>"),
                    # 默认为ali-sh
                    Hidden('machine_region', value=init_region),
                    Hidden('next', value=next_url),
                    Hidden('origin', value=origin),
                    Field('password',
                          css_class="form-control",
                          placeholder='请设置密码,至少包含8位字符'),
                    Field('password_repeat',
                          css_class="form-control",
                          placeholder='请再输入一次密码'),
                    Field('phone',
                          css_class="form-control",
                          placeholder='请输入手机号'),
                    AppendedText(
                        'captcha_code',
                        '<img id="captcha_code" src="/captcha" /> <a href="javascript:void(0)" onclick="refresh();">看不清,换一张</a>  ',
                        css_class='input-xlarge',
                        placeholder='图片验证码'),
                    AppendedText(
                        'phone_code',
                        '<a href="javascript:void(0)" id="PhoneCodeBtn" onclick="getPhoneCode();">点击发送验证码</a>  ',
                        css_class='input-xlarge',
                        placeholder='手机验证码'),
                    HTML(
                        """<div class="linkfw text-center">点击注册表示你已阅读并同意《<a href="http://www.goodrain.com/goodrainlaws.html" target="_blank">云帮服务条款</a>》</div>"""
                    ),
                    FormActions(
                        Submit('register',
                               u'注册',
                               css_class='btn btn-lg btn-success btn-block')),
                    HTML("""<p class="text-center">或使用以下账号注册</p>"""),
                    HTML(
                        """<a href="/wechat/login{0}" class="weixin"><img src="static/www/images/weixin.png">微信</a>"""
                        .format(prefix_url)),
                    HTML(
                        """<div class="linkregister text-center">直接<a href="/login{0}">登录</a></div>"""
                        .format(prefix_url)),
                    # HTML("""<a href="http://www.goodrain.com/" class="linkgood text-center">goodrain.com</a>"""),
                    css_class="login-wrap"))
        else:
            self.helper.layout = Layout(
                Div(
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control") if tenant_name is None else
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control",
                          readonly="readonly",
                          value=tenant_name),
                    Field('nick_name',
                          css_class="form-control",
                          placeholder='请输入用户名(可使用小写英文字母、数字、下划线及中划线)'),
                    Field('email',
                          css_class="form-control",
                          placeholder='请输入邮箱(选填)'),
                    HTML("<hr/>"),
                    Hidden('machine_region', value=init_region),
                    Hidden('next', value=next_url),
                    Hidden('origin', value=origin),
                    Field('password',
                          css_class="form-control",
                          placeholder='请设置密码,至少包含8位字符'),
                    Field('password_repeat',
                          css_class="form-control",
                          placeholder='请再输入一次密码'),
                    Field('phone',
                          css_class="form-control",
                          placeholder='请输入手机号'),
                    AppendedText(
                        'captcha_code',
                        '<img id="captcha_code" src="/captcha" /> <a href="javascript:void(0)" onclick="refresh();">看不清,换一张</a>  ',
                        css_class='input-xlarge',
                        placeholder='验证码'),
                    AppendedText(
                        'phone_code',
                        '<a href="javascript:void(0)" id="PhoneCodeBtn" onclick="getPhoneCode();">点击发送验证码</a>  ',
                        css_class='input-xlarge',
                        placeholder='手机验证码'),
                    HTML(
                        """<div class="linkfw text-center">点击注册表示你已阅读并同意《<a href="http://www.goodrain.com/goodrainlaws.html" target="_blank">云帮服务条款</a>》</div>"""
                    ),
                    FormActions(
                        Submit('register',
                               u'注册',
                               css_class='btn btn-lg btn-success btn-block')),
                    HTML(
                        """<div class="linkregister text-center">直接<a href="/login{0}">登录</a></div>"""
                        .format(prefix_url)),
                    # HTML("""<a href="http://www.goodrain.com/" class="linkgood text-center">goodrain.com</a>"""),
                    css_class="login-wrap"))
        self.helper.form_id = 'form-normal-reg'
        self.helper.form_class = 'form-horizontal'
Exemple #58
0
    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout('email', 'password', 'password1')
        self.helper.add_input(Submit('submit', 'Register'))
Exemple #59
0
 def __init__(self, *args, **kwargs):
     prefix_url = ""
     if len(kwargs) > 0:
         if kwargs.get("next_url") is not None:
             next_url = kwargs["next_url"]
             if next_url != "":
                 prefix_url += "&next={0}".format(next_url)
             kwargs.pop("next_url")
         if kwargs.get("origin") is not None:
             origin = kwargs["origin"]
             if origin != "":
                 prefix_url += "&origin={0}".format(origin)
             kwargs.pop("origin")
     if len(prefix_url) > 1:
         prefix_url = "?" + prefix_url[1:]
     super(UserLoginForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper(self)
     self.helper.form_tag = False
     self.helper.form_show_labels = False
     if settings.MODULES["User_Register"]:
         if settings.MODULES["WeChat_Module"]:
             self.helper.layout = Div(
                 Field('email',
                       css_class="form-control",
                       placeholder='邮箱/手机号/用户名'),
                 Field('password',
                       css_class="form-control",
                       placeholder='密码'),
                 HTML(
                     """<div class="checkbox clearfix"><label><input type="checkbox">下次自动登录</label><a href="/account/begin_password_reset" class="pull-right">忘记密码了?</a></div>"""
                 ),
                 FormActions(
                     Submit('login',
                            u'登录',
                            css_class='btn btn-lg btn-success btn-block')),
                 HTML(
                     """<p class="text-center">或使用以下账号登录</p><a href="/wechat/login{0}" class="weixin"><img src='/static/www/images/weixin.png'>&nbsp;微信</a>"""
                     .format(prefix_url)),
                 # HTML("""<div class="linkregister text-center">现在<a href="/register{0}">注册</a></div>""".format(prefix_url)),
                 css_class='login-wrap',
                 style="background: #FFFFFF;",
             )
         else:
             self.helper.layout = Div(
                 Field('email',
                       css_class="form-control",
                       placeholder='邮箱/手机号/用户名'),
                 Field('password',
                       css_class="form-control",
                       placeholder='密码'),
                 HTML(
                     """<div class="checkbox clearfix"><label><input type="checkbox">下次自动登录</label><a href="/account/begin_password_reset" class="pull-right">忘记密码了?</a></div>"""
                 ),
                 FormActions(
                     Submit('login',
                            u'登录',
                            css_class='btn btn-lg btn-success btn-block')),
                 # HTML("""<div class="linkregister text-center">现在<a href="/register{0}">注册</a></div>""".format(prefix_url)),
                 css_class='login-wrap',
                 style="background: #FFFFFF;",
             )
     else:
         self.helper.layout = Div(
             Field('email',
                   css_class="form-control",
                   placeholder='邮箱/手机号/用户名'),
             Field('password', css_class="form-control", placeholder='密码'),
             FormActions(
                 Submit('login',
                        u'登录',
                        css_class='btn btn-lg btn-success btn-block')),
             css_class='login-wrap',
             style="background: #FFFFFF;",
         )
     self.helper.help_text_inline = True
     self.helper.error_text_inline = True
     self.helper.form_id = 'form-user-login'
     self.helper.form_class = 'form-horizontal'
Exemple #60
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper(self)
     self.helper.layout.append(Submit('unsubscribe_btn', 'unSubscribe'))