Пример #1
0
    def __init__(self, form: Form, user: User, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # TODO: This is ugly - makes wwwforms have a circular reference to wwwapp, and should it even be hardcoded to 'latest'?
        current_year = Camp.objects.latest()

        self.form = form
        self.user = user
        self.questions = form.questions.all()
        answers_qs = FormQuestionAnswer.objects.prefetch_related(
            'question').filter(question__in=self.questions, user=user).all()
        self.answers = {}
        for question in self.questions:
            field_name = self.field_name_for_question(question)
            field_type = self.FIELD_TYPES[question.data_type]

            self.answers[field_name] = next(
                filter(lambda x: x.question == question, answers_qs), None)
            value = self.answers[field_name].value if self.answers[
                field_name] is not None else None

            field_kwargs = {}
            if question.data_type in (FormQuestion.TYPE_CHOICE,
                                      FormQuestion.TYPE_MULTIPLE_CHOICE,
                                      FormQuestion.TYPE_SELECT):
                field_kwargs['queryset'] = question.options.all()
                field_kwargs['blank'] = not question.is_required

            if question.data_type == FormQuestion.TYPE_PHONE:
                # Remove after https://github.com/stefanfoulis/django-phonenumber-field/commit/1da0b6a19298934d277e456206c8f222d9ac83ae is released
                field_kwargs['region'] = getattr(settings,
                                                 "PHONENUMBER_DEFAULT_REGION",
                                                 None)

            self.fields[field_name] = field_type(label=question.title,
                                                 initial=value,
                                                 required=question.is_required
                                                 and not question.is_locked,
                                                 disabled=question.is_locked,
                                                 **field_kwargs)

            if question.data_type == FormQuestion.TYPE_PHONE:
                # django-phonenumber-field defaults to a landline phone in error messages without a way to change it
                # Also, localize the error message, and remove the info that you can use international call prefix
                # because who cares
                region = getattr(settings, "PHONENUMBER_DEFAULT_REGION", None)
                if region:
                    number = phonenumbers.example_number_for_type(
                        region, phonenumbers.PhoneNumberType.MOBILE)
                    example_number = phonenumber_field.phonenumber.to_python(
                        number).as_national
                    self.fields[field_name].error_messages[
                        "invalid"] = format_lazy(
                            "Wpisz poprawny numer telefonu (np. {example_number})",
                            example_number=example_number)

            if question.data_type == FormQuestion.TYPE_DATE:
                if question == form.arrival_date:
                    self.fields[field_name].widget = forms.widgets.DateInput(
                        attrs={
                            'data-default-date': current_year.start_date or '',
                            'data-start-date': current_year.start_date or '',
                            'data-end-date': current_year.end_date or ''
                        })
                if question == form.departure_date:
                    self.fields[field_name].widget = forms.widgets.DateInput(
                        attrs={
                            'data-default-date': current_year.end_date or '',
                            'data-start-date': current_year.start_date or '',
                            'data-end-date': current_year.end_date or ''
                        })

        self.helper = FormHelper(self)
        self.helper.include_media = False
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-9'

        self.helper.layout.fields.append(
            FormActions(
                StrictButton('Zapisz',
                             type='submit',
                             css_class='btn-outline-primary btn-lg m-3'),
                css_class='text-right row',
            ))
class EstablishingForm1(BaseModelForm):
    def __init__(self, *args, **kwargs):
        super(EstablishingForm1, self).__init__(*args, **kwargs)
        self.fields['name'].label = "Company name"
        self.fields['description'].label = "Please describe your business"
        self.fields[
            'url'].label = "Please share a url to the website with your product"
        self.fields['sectors'].label = "What sectors do you operate in?"
        self.fields[
            'service_pic'].label = "Please provide a picture that shows your product/service (jpeg, png, gif)"
        self.fields[
            'service_videos'].label = "Please provide a link to the video that shows your product/service. " \
                                      "[This can be a link to youtube or vimeo]"
        self.fields[
            'challenge_to_solve'].label = "What challenges or need is your idea trying to solve?"
        self.fields[
            'challenge_faced'].label = "What challenges are you facing?"
        self.fields['other_challenges'].label = ""

    name = forms.CharField()
    logo = forms.ImageField(validators=[validate_img], required=False)
    service_pic = forms.ImageField(required=True)
    service_videos = forms.URLField(required=False)
    other_challenges = forms.CharField(widget=forms.Textarea(), required=False)
    url = forms.URLField(required=False)
    description = forms.CharField(widget=forms.Textarea(), )
    sectors = forms.MultipleChoiceField(
        required=True,
        choices=(
            ('agriculture', "Agriculture"),
            ('manufacturing', "Manufacturing and Assembly"),
            ('financial', "Financial Services"),
            ('renewable', "Renewable Energy"),
            ('infosec', "Information Security"),
            ('education', "Education"),
            ('health', "Healthcare & Services"),
            ('infrastructure', "Infrastructure"),
            ('transport', "Transport"),
        ),
        widget=forms.CheckboxSelectMultiple,
    )

    challenge_to_solve = forms.CharField(widget=forms.Textarea(), )

    challenge_faced = forms.MultipleChoiceField(
        choices=(
            ('financial_articulation', "I can't articulate my financials"),
            ('risk_management', "I do not know how to manage risk"),
            ('runway_ending', "Running out of start up capital"),
            ('business_differentiator',
             "Figuring out why my business is different"),
            ('team_members', "Getting qualified team members"),
            ('others', "Others"),
        ),
        widget=forms.CheckboxSelectMultiple,
    )

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.layout = Layout(
        Field('name', css_class='input-length3 form-control text-small'),
        Field('description',
              rows="3",
              css_class='input-length3 form-control text-large'),
        Field('url',
              css_class='input-length3 form-control text-small',
              placeholder='https://innovation.com'),
        Field('service_pic', css_class='file-upload'),
        Field('service_videos',
              css_class='input-length3 form-control text-small',
              placeholder='https://www.youtube.com/watch?v=eedeXTWZUn8'),
        InlineCheckboxes('sectors'),
        Field('other_sectors',
              css_class='input-length3 form-control text-small'),
        Field('challenge_to_solve',
              rows="3",
              css_class='input-length3 form-control text-large'),
        InlineCheckboxes('challenge_faced', ),
        Field('other_challenges',
              css_class='text-small',
              placeholder="Other Challenges"),
        Field('logo', css_class='file-upload'),
        FormActions(
            Submit('establishing_form_1',
                   'Next',
                   css_class="cancelBtn btnNext"), ))

    class Meta:
        model = Innovation
        fields = ('name', 'description', 'url', 'sectors', 'other_sectors',
                  'challenge_faced', 'challenge_to_solve', 'logo',
                  'service_pic', 'other_challenges', 'service_videos')
Пример #3
0
from django_date_extensions.fields import ApproximateDateFormField
from base.fields.extra import AdvancedFileInput
from base.fields.widgets import ReadOnlyIconField
from tagging.forms import TagField

from search.forms import fields as search_fields

from ..models import Release, Relation, Media, License, Label, ReleaseAlbumartists
from ..util.storage import get_file_from_url

log = logging.getLogger(__name__)

ACTION_LAYOUT = FormActions(
    HTML(
        '<button type="submit" name="save" value="save" class="btn btn-primary pull-right ajax_submit" id="submit-id-save-i-classicon-arrow-upi"><i class="icon-save icon-white"></i> Save</button>'
    ),
    HTML(
        '<button type="reset" name="reset" value="reset" class="reset resetButton btn btn-abort pull-right" id="reset-id-reset"><i class="icon-trash"></i> Cancel</button>'
    ),
)

MAX_TRACKNUMBER = 100 + 1


class ReleaseActionForm(Form):

    publish = forms.BooleanField(label=_('Save & Publish'), required=False)

    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', False)
        super(ReleaseActionForm, self).__init__(*args, **kwargs)
Пример #4
0
    def __init__(self, *args, **kwargs):
        super(CompraForm, self).__init__(*args, **kwargs)
        # self.fields['fecha_emision'] = DateField(input_formats=['%d/%m/%Y'], widget=forms.DateTimeInput(attrs={
        #     'class': 'form-control datetimepicker-input',
        #     'data-target': '#datetimepicker1'
        # }))
        codigos_comprobante = ["01", "03", "99"]
        self.fields['fecha_emision'] = DateField(
            input_formats=['%d/%m/%Y'],
            widget=forms.DateInput(
                attrs={
                    'class': 'form-control datetimepicker-input',
                    'data-target': '#datetimepicker1'
                }))

        self.fields['fecha_vencimiento'] = DateField(
            input_formats=['%d/%m/%Y'],
            widget=forms.DateInput(
                attrs={
                    'class': 'form-control datetimepicker-input',
                    'data-target': '#datetimepicker1'
                }))
        codigos_comprobante = ["01", "03", "99"]
        self.fields[
            'tipo_comprobante'].queryset = TipoComprobantePago.objects.filter(
                codigo__in=codigos_comprobante)

        # self.fields['proveedor'].widget = autocomplete.ModelSelect2(url='compra:proveedor_autocomplete',)
        self.fields['base_imponible'].widget.attrs['readonly'] = True
        self.fields['igv'].widget.attrs['readonly'] = True
        # self.fields['fecha_vencimiento'].widget.attrs['readonly'] = True

        self.helper = FormHelper()
        self.helper.attrs['autocomplete'] = "off"
        self.helper.form_method = 'post'
        self.helper.form_class = 'js-validate form-vertical'

        self.helper.layout = Layout(
            Row(
                Fieldset(
                    "Comprobate",
                    Div(Field('proveedor', css_class='input-required'),
                        css_class='col-md-3'),
                    Div(Field('serie_comprobante', css_class='input-required'),
                        css_class='col-md-2'),
                    Div(Field('nro_comprobante', css_class='input-required'),
                        css_class='col-md-3'),
                    Div(Field('fecha_emision', css_class='input-required'),
                        css_class='col-md-2'),
                    Div(Field('fecha_vencimiento', ), css_class='col-md-2'),
                    css_class="scheduler-border",
                )),
            Fieldset(
                "Pago",
                Row(Div(Field('tipo_comprobante', css_class='input-required'),
                        css_class='col-md-4'),
                    Div(Field('tipo_moneda', css_class='input-required'),
                        css_class='col-md-2'),
                    Div(Field('total', css_class='input-required'),
                        css_class='col-md-2'),
                    Div(Field('base_imponible', css_class='input-required'),
                        css_class='col-md-2'),
                    Div(Field('igv', css_class='input-required'),
                        css_class='col-md-2'),
                    css_class="scheduler-border"),
            ),
            Row(FormActions(
                smtSave(),
                btnCancel(),
            ), ),
        )
Пример #5
0
class NewGraphRuleForm(forms.Form):
    """
    Add new graph rule
    """
    rule_packages_choices = ()
    rule_langs_choices = ()
    rule_relbranch_choices = ()

    rule_name = forms.CharField(
        label='Graph Rule Name',
        help_text='Rule will be saved in slug form.',
        required=True,
    )
    rule_relbranch = forms.ChoiceField(
        label='Release Branch',
        choices=rule_relbranch_choices,
        help_text=
        'Graph will be generated for selected release branch following branch mapping.',
        required=True)
    rule_packages = TextArrayField(
        label='Packages',
        widget=forms.CheckboxSelectMultiple,
        choices=rule_packages_choices,
        help_text="Selected packages will be included in this rule.",
        required=True)
    lang_selection = forms.ChoiceField(
        label='Languages Selection',
        choices=[('pick', 'Pick release branch specific languages'),
                 ('select', 'Select languages')],
        initial='pick',
        widget=forms.RadioSelect,
        required=True,
        help_text=
        "Either pick language set associated with selected release branch or choose languages."
    )
    rule_langs = TextArrayField(
        label='Languages',
        widget=forms.CheckboxSelectMultiple,
        choices=rule_langs_choices,
        help_text="Selected languages will be included in this rule.",
        required=False)

    def __init__(self, *args, **kwargs):
        self.rule_packages_choices = kwargs.pop('packages')
        self.rule_langs_choices = kwargs.pop('languages')
        self.rule_relbranch_choices = kwargs.pop('branches')
        super(NewGraphRuleForm, self).__init__(*args, **kwargs)
        self.fields['rule_packages'].choices = self.rule_packages_choices
        self.fields['rule_langs'].choices = self.rule_langs_choices
        self.fields['rule_relbranch'].choices = self.rule_relbranch_choices
        super(NewGraphRuleForm, self).full_clean()

    helper = FormHelper()
    helper.form_method = 'POST'
    helper.form_action = '/settings/graph-rules/new'
    helper.form_class = 'dynamic-form'
    helper.error_text_inline = True
    helper.form_show_errors = True

    helper.layout = Layout(
        Div(
            Field('rule_name',
                  css_class="form-control",
                  onkeyup="showRuleSlug()"),
            Field('rule_relbranch', css_class="selectpicker"),
            InlineCheckboxes('rule_packages', css_class="checkbox"),
            InlineRadios('lang_selection', id="lang_selection_id"),
            InlineCheckboxes('rule_langs', css_class="checkbox"),
            HTML("<hr/>"),
            FormActions(Submit('addRule', 'Add Graph Rule'),
                        Reset('reset', 'Reset'))))

    def is_valid(self):
        return False if len(self.errors) >= 1 else True
Пример #6
0
class KegForm(forms.Form):
    keg_size = forms.ChoiceField(choices=keg_sizes.CHOICES,
        initial=keg_sizes.HALF_BARREL,
        required=True)

    initial_volume = forms.FloatField(label='Initial Volume', initial=0.0,
        required=False, help_text='Keg\'s Initial Volume')

    beer_name = forms.CharField(required=False)  # legacy
    brewer_name = forms.CharField(required=False)  # legacy

    beverage_name = forms.CharField(label='Beer Name', required=False)
    beverage_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    producer_name = forms.CharField(label='Brewer', required=False)
    producer_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    style_name = forms.CharField(required=True, label='Style',
      help_text='Example: Pale Ale, Stout, etc.')

    description = forms.CharField(max_length=256, label='Description',
        widget=forms.Textarea(), required=False,
        help_text='Optional user-visible description of the keg.')
    notes = forms.CharField(label='Notes', required=False, widget=forms.Textarea(),
        help_text='Optional private notes about this keg, viewable only by admins.')
    connect_to = forms.ModelChoiceField(queryset=ALL_TAPS, label='Connect To',
        required=False,
        help_text='If selected, immediately activates the keg on this tap. '
            '(Any existing keg will be ended.)')

    helper = FormHelper()
    helper.form_class = 'form-horizontal beer-select'
    helper.layout = Layout(
        Field('beverage_name', css_class='input-xlarge'),
        Field('beverage_id', type='hidden'),
        Field('producer_name', css_class='input-xlarge'),
        Field('producer_id', type='hidden'),
        Field('style_name', css_class='input-xlarge'),
        Field('keg_size', css_class='input-xlarge'),
        Field('initial_volume', css_class='input-volume'),
        Field('description', css_class='input-block-level', rows='3'),
        Field('notes', css_class='input-block-level', rows='3'),
        Field('connect_to', css_class='input-block-level'),
        FormActions(
            Submit('submit_add_keg', 'Save', css_class='btn-primary'),
        )
    )

    def clean_beverage_name(self):
        beverage_name = self.cleaned_data.get('beverage_name')
        if not beverage_name:
            beverage_name = self.cleaned_data.get('beer_name')
            if not beverage_name:
                raise forms.ValidationError('Must specify a beverage name')
            self.cleaned_data['beverage_name'] = beverage_name
        return beverage_name

    def clean_producer_name(self):
        producer_name = self.cleaned_data.get('producer_name')
        if not producer_name:
            producer_name = self.cleaned_data.get('brewer_name')
            if not producer_name:
                raise forms.ValidationError('Must specify a producer name')
            self.cleaned_data['producer_name'] = producer_name
        return producer_name

    def save(self):
        if not self.is_valid():
            raise ValueError('Form is not valid.')
        keg_size = self.cleaned_data.get('keg_size')
        if keg_size != 'other':
            full_volume_ml = None
        else:
            full_volume_ml = self.cleaned_data.get('initial_volume')

        # TODO(mikey): Support non-beer beverage types.
        cd = self.cleaned_data
        b = get_kegbot_backend()
        keg = b.create_keg(beverage_name=cd['beverage_name'], producer_name=cd['producer_name'],
            beverage_type='beer', style_name=cd['style_name'], keg_type=cd['keg_size'],
            full_volume_ml=full_volume_ml, notes=cd['notes'], description=cd['description'])

        tap = cd['connect_to']
        if tap:
            if tap.is_active():
                b.end_keg(tap.current_keg)
            b.attach_keg(tap, keg)

        return keg
Пример #7
0
from ajax_select.fields import AutoCompleteSelectField
from ajax_select import make_ajax_field

from django.forms.widgets import FileInput, HiddenInput

#from floppyforms.widgets import DateInput
from tagging.forms import TagField
from ac_tagging.widgets import TagAutocompleteTagIt

from lib.widgets.widgets import ReadOnlyIconField

ACTION_LAYOUT = action_layout = FormActions(
    HTML(
        '<button type="submit" name="save" value="save" class="btn btn-primary pull-right ajax_submit" id="submit-id-save-i-classicon-arrow-upi"><i class="icon-save icon-white"></i> Save</button>'
    ),
    HTML(
        '<button type="reset" name="reset" value="reset" class="reset resetButton btn btn-secondary pull-right" id="reset-id-reset"><i class="icon-trash"></i> Cancel</button>'
    ),
)
ACTION_LAYOUT_EXTENDED = action_layout = FormActions(
    Field('publish', css_class='input-hidden'),
    HTML(
        '<button type="submit" name="save" value="save" class="btn btn-primary pull-right ajax_submit" id="submit-id-save-i-classicon-arrow-upi"><i class="icon-save icon-white"></i> Save</button>'
    ),
    HTML(
        '<button type="submit" name="save-and-publish" value="save" class="btn pull-right ajax_submit save-and-publish" id="submit-id-save-i-classicon-arrow-upi"><i class="icon-bullhorn icon-white"></i> Save & Publish</button>'
    ),
    HTML(
        '<button type="reset" name="reset" value="reset" class="reset resetButton btn btn-secondary pull-right" id="reset-id-reset"><i class="icon-trash"></i> Cancel</button>'
    ),
)
Пример #8
0
    def __init__(self, *args, **kwargs):
        super(WineForm, self).__init__(*args, **kwargs)
        self.fields['wineType'].choices = WINE_TYPES
        # self.fields['region'].choices  =  [(x,x.region) for x in Region.approved.all()]
        self.fields['producer'].choices = [(x, x.producer)
                                           for x in Producer.approved.all()]
        # self.fields['appelation'].choices = [(x,x.appelation) for x in Appelation.approved.all()]
        # self.fields['tag'].choices = [(x,x.tag) for x in Tag.approved.all()]
        # self.fields['cepage'].choices = [(x,x.cepage) for x in Cepage.approved.all()]

        self.helper = FormHelper()
        self.form_id = 'wine_form'
        self.label_class = 'col-lg-12'
        self.field_class = 'col-lg-12'
        # self.form_method = 'post'
        self.form_class = 'form_horizontal'
        self.form_action = reverse('corewine:tasting')

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

        self.helper.layout = Layout(
            Fieldset(
                _('Type'),
                InlineRadios('wineType'),
            ),
            Fieldset(
                _('General Information'),
                Div(Field('name'), css_class='col-lg-3'),
                Div(Field('year'), css_class='col-lg-3'),
                Div('code_saq', css_class='col-lg-3'),
                Div('date', css_class='col-lg-3'),
                Div('cepage', css_class='col-lg-3'),
                Div(AppendedText('alcool', '%'), css_class="col-lg-3"),
                Div(AppendedText('price', '$'), css_class='col-lg-3'),
            ),
            Fieldset(
                _('Geography'),
                Div(Field('country'), css_class='col-lg-3'),
                Div(Field('appelation'), css_class='col-lg-3'),
                Div(Field('producer'), css_class='col-lg-3'),
                Div(Field('region'), css_class='col-lg-3'),
            ),
            Fieldset(
                _('Eye'),
                Div(Field('teint'), css_class='col-lg-2'),
                Div('aroma', css_class='col-lg-2'),
            ),
            Fieldset(
                _('Nose'),
                Div('nose_intensity', css_class='col-lg-2'),
            ),
            Fieldset(
                _('Mouth'),
                Div('mouth_intensity', css_class='col-lg-2'),
                Div('persistance', css_class='col-lg-2'),
                Div('taste', css_class='col-lg-2'),
                Div('tanin', css_class='col-lg-2'),
                Div('acidity', css_class='col-lg-2'),
            ),
            Fieldset(
                _('Extra information'),
                Div('tag', css_class='col-lg-4'),
                Div('rating', css_class='col-lg-4'),
            ), FormActions('Sign in', css_class='btn-primary'))
Пример #9
0
class KegForm(forms.Form):
    keg_size = forms.ChoiceField(choices=keg_sizes.CHOICES,
                                 initial=keg_sizes.HALF_BARREL,
                                 required=True)

    initial_volume = forms.FloatField(
        label='Initial Volume (Liters)',
        initial=0.0,
        required=False,
        help_text='Keg\'s Initial Volume in Liters')

    beer_name = forms.CharField(required=False)  # legacy
    brewer_name = forms.CharField(required=False)  # legacy

    beverage_name = forms.CharField(label='Beer Name', required=False)
    beverage_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    producer_name = forms.CharField(label='Brewer', required=False)
    producer_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    style_name = forms.CharField(required=True,
                                 label='Style',
                                 help_text='Example: Pale Ale, Stout, etc.')

    description = forms.CharField(
        max_length=256,
        label='Description',
        widget=forms.Textarea(),
        required=False,
        help_text='User-visible description of the Keg.')
    notes = forms.CharField(
        label='Notes',
        required=False,
        widget=forms.Textarea(),
        help_text='Private notes about this keg, viewable only by admins.')

    helper = FormHelper()
    helper.form_class = 'form-horizontal beer-select'
    helper.layout = Layout(
        Field('beverage_name', css_class='input-xlarge'),
        Field('beverage_id', type='hidden'),
        Field('producer_name', css_class='input-xlarge'),
        Field('producer_id', type='hidden'),
        Field('style_name', css_class='input-xlarge'),
        Field('keg_size', css_class='input-xlarge'),
        Div(Field('initial_volume', css_class='input-volume', type='hidden'),
            css_class='variable-units'), Field('description'), Field('notes'),
        FormActions(Submit('submit_add_keg', 'Save',
                           css_class='btn-primary'), ))

    def clean_beverage_name(self):
        beverage_name = self.cleaned_data.get('beverage_name')
        if not beverage_name:
            beverage_name = self.cleaned_data.get('beer_name')
            if not beverage_name:
                raise forms.ValidationError('Must specify a beverage name')
            self.cleaned_data['beverage_name'] = beverage_name
        return beverage_name

    def clean_producer_name(self):
        producer_name = self.cleaned_data.get('producer_name')
        if not producer_name:
            producer_name = self.cleaned_data.get('brewer_name')
            if not producer_name:
                raise forms.ValidationError('Must specify a producer name')
            self.cleaned_data['producer_name'] = producer_name
        return producer_name

    def save(self):
        if not self.is_valid():
            raise ValueError('Form is not valid.')
        keg_size = self.cleaned_data.get('keg_size')
        if keg_size != 'other':
            full_volume_ml = None
        else:
            full_volume_ml = self.cleaned_data.get('initial_volume')

        # TODO(mikey): Support non-beer beverage types.
        cd = self.cleaned_data
        b = get_kegbot_backend()
        keg = b.create_keg(beverage_name=cd['beverage_name'],
                           producer_name=cd['producer_name'],
                           beverage_type='beer',
                           style_name=cd['style_name'],
                           keg_type=cd['keg_size'],
                           full_volume_ml=full_volume_ml,
                           notes=cd['notes'],
                           description=cd['description'])
        return keg
Пример #10
0
class TicketForm(forms.ModelForm):
    helper = FormHelper()
    helper.layout = Layout(
        Fieldset(
            '',
            Div(
                Div(
                    Div('customer'),
                    Div('address'),
                    css_class='col',
                ),
                Div(Div('salesperson'),
                    Div(
                        PrependedText(
                            'phone',
                            '<i class="fa fa-phone" aria-hidden="true"></i>')),
                    Div(
                        PrependedText(
                            'email',
                            '<i class="fa fa-envelope-o" aria-hidden="true"></i>'
                        )),
                    css_class='col'),
                css_class="row",
            ),
            Div(
                Div('work_requested', css_class='col'),
                css_class='row',
            ),
            Div(
                Div('work_completed', css_class='col'),
                css_class='row',
            ),
            Div(
                Div('installers', css_class='col self.helper.form_id'),
                Div(PrependedText(
                    'date_completed',
                    '<i class="fa fa-calendar" aria-hidden="true"></i>'),
                    css_class='col'),
                css_class='row',
            ),
        ),
        FormActions(
            Submit('submit', 'Save', css_class="btn btn-outline-success"),
            HTML(
                """<a href="{% url "ticket-list" %}" class="btn btn-secondary">Cancel</a>"""
            ),
            HTML("""{% if object %}
                    <a href="{% url "ticket-delete" object.id %}"
                    class="btn btn-outline-danger pull-right">
                    Delete <i class="fa fa-trash-o" aria-hidden="true"></i></button></a>
                    {% endif %}"""),
        ))

    class Meta:
        model = Ticket
        fields = (
            'customer',
            'salesperson',
            'address',
            'phone',
            'email',
            'installers',
            'work_requested',
            'work_completed',
            'date_completed',
        )
        widgets = {
            'address': forms.Textarea(attrs={'rows': 4}),
            'email': forms.TextInput(attrs={'placeholder': 'Email'}),
            'phone': forms.TextInput(attrs={'placeholder': 'Phone'}),
            'work_requested': forms.Textarea(attrs={'rows': 10}),
            'work_completed': forms.Textarea(attrs={'rows': 10}),
            'date_completed': forms.DateInput(format='%b %d, %Y'),
        }

    def __init__(self, *args, **kwargs):
        super(TicketForm, self).__init__(*args, **kwargs)
        self.fields['address'].label = "Job Address"
        self.fields['email'].label = ""
        self.fields['phone'].label = ""
Пример #11
0
    def __init__(self, *args, **kwargs):
        """Initialize with a FormHelper and default submit action."""

        super(CrispyModelForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout.append(FormActions(Submit('submit', "Submit")))
Пример #12
0
    def __init__(self, *args, **kwargs):
        super(RegistrationEnterpriseAssociationForm,
              self).__init__(*args, **kwargs)
        self.fields['name'] = forms.CharField(
            label=capfirst(_(u'Enterprise')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['association_name'] = forms.CharField(
            label=capfirst(_(u'Association')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )

        self.fields['acept'] = forms.BooleanField(
            label=capfirst(_(u'I accept the Terms of Service and Privacy Policy.')), required=True,
            # widget=forms.CheckboxInput(),
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['logo'] = forms.ImageField(
            label=capfirst(_(u'logo')), required=False,
            initial='enterprises/default.png',
            help_text=u'<small class="help-error"></small> %s' % _(
                u'Available formats are JPG, GIF, and PNG.'),
        )
        self.fields['solution'].required = True
        self.fields['solution'].help_text = u'<small class="help-error"></small> %s' % _(
            u' ')
        self.fields['type_e'].help_text = u'<small class="help-error"></small> %s' % _(
            u' ')
        self.fields['tax_id'].help_text = u'<small class="help-error"></small> %s' % _(
            u' ')

        self.helper = FormHelper()
        self.helper.form_id = 'form'
        self.helper.form_class = 'js-validate form-vertical'
        self.helper.layout = Layout(

            TabHolder(
                Tab(_('Enterprise'),
                    Row(
                        Div(Field('name', autofocus=True, css_class='input-required'),
                    css_class='col-md-6'),
                        Div(Field('tax_id', css_class='input-required', ),
                    css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field('association_name', css_class='input-required',),
                            css_class='col-md-6'),
                        Div(Field('type_e', css_class='input-required', ),
                            css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field('solution', css_class='input-required',),
                            css_class='col-md-6'),
                    ),


                    ),
                Tab(_('Image'),
                    Field('logo', css_class="")
                    ),
            ),
            Row(
                Div(Field('acept', css_class='input-required',),
                    css_class='col-md-12'),
            ),
            Row(
                FormActions(
                    smtSave(),
                    btnCancel(),
                    btnReset(),
                ),
            ),
        )
Пример #13
0
    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['first_name'] = forms.CharField(
            label=capfirst(_(u'first name')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['last_name'] = forms.CharField(
            label=capfirst(_(u'last name')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['identity_num'] = forms.CharField(
            label=dict((x, y)
                       for x, y in IDENTITY_TYPE_CHOICES)[NID], required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['association_name'] = forms.CharField(
            label=capfirst(_(u'Association')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['enterprise_name'] = forms.CharField(
            label=capfirst(_(u'Enterprise')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['enterprise_tax_id'] = forms.CharField(
            label=capfirst(_(u'Tax id')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['enterprise_type_e'] = forms.ChoiceField(
            label=capfirst(_(u'Type')), required=True,
            # widget=forms.RadioSelect(),
            choices=(('', '----------'),) + TYPE_CHOICES,

            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['solution'] = forms.ModelChoiceField(
            label=capfirst(_(u'Solution')), required=True,
            queryset=Solution.objects.filter(is_active=True),
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['acept'] = forms.BooleanField(
            label=capfirst(_(u'I accept the Terms of Service and Privacy Policy.')), required=True,
            # widget=forms.CheckboxInput(),
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['photo'] = forms.ImageField(
            label=capfirst(_(u'Photo')), required=False,
            initial='persons/default.png',
            help_text=u'<small class="help-error"></small> %s' % _(
                u'Available formats are JPG, GIF, and PNG.'),
        )

        self.helper = FormHelper()
        self.helper.form_class = 'js-validate form-vertical'
        self. helper.layout = Layout(

            TabHolder(
                Tab(
                    _('Account Info'),
                    Row(
                        Div(Field('username', autofocus=True, css_class='input-required'),
                    css_class='col-md-6'),
                        Div(Field('email', ),
                    css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field('password1',),
                                    css_class='col-md-6'),
                        Div(Field('password2', ),
                                    css_class='col-md-6'),
                    ),

                    Row(
                        Div(Field('enterprise_name',),
                                    css_class='col-md-6'),
                        Div(Field('enterprise_tax_id', ),
                                    css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field('association_name',),
                                    css_class='col-md-6'),
                        Div(Field('enterprise_type_e', ),
                                    css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field('solution',),
                                    css_class='col-md-6'),
                    ),


                ),
                Tab(
                    _('Personal Info'),
                    Row(
                        Div(Field('first_name',),
                    css_class='col-md-6'),
                        Div(Field('last_name', ),
                    css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field('identity_num',),
                                    css_class='col-md-6'),
                    ),
                ),
                Tab(_('Image'),
                    Field('photo', css_class="")
                    ),
            ),
            Row(
                Div(Field('acept',),
                    css_class='col-md-12'),
            ),

            FormActions(
                Submit('submit', _('Sign up'),
                       css_class='btn-success pull-right'),
            ),
        )
Пример #14
0
class MessageForm(forms.Form):
    text_input = forms.CharField()
    text_input_a = forms.CharField()
    text_input_b = forms.CharField()
    text_input_c = forms.CharField()

    textarea = forms.CharField(widget=forms.Textarea(), )

    radio_buttons = forms.ChoiceField(
        choices=
        (('option_one',
          "Option one is this and that be sure to include why it's great"),
         ('option_two',
          "Option two can is something else and selecting it will deselect option one"
          )),
        widget=forms.RadioSelect,
        initial='option_two',
    )

    checkboxes = forms.MultipleChoiceField(
        choices=
        (('option_one',
          "Option one is this and that be sure to include why it's great"),
         ('option_two',
          'Option two can also be checked and included in form results'),
         ('option_three',
          'Option three can yes, you guessed it also be checked and included in form results'
          )),
        initial='option_one',
        widget=forms.CheckboxSelectMultiple,
        help_text=
        "<strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.",
    )

    grouped_checkboxes = forms.MultipleChoiceField(
        choices=(
            ('Group 1', ((1, "Option one"), (2, "Option two"),
                         (3, "Option three"))),
            ('Group 2', ((4, "Option four"), (5, "Option five"),
                         (6, "Option six"))),
        ),
        initial=(1, ),
        widget=forms.CheckboxSelectMultiple,
    )

    multicolon_select = forms.MultipleChoiceField(
        choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')), )

    # Bootstrap4
    helper = FormHelper()
    helper.layout = Layout(
        Field('text_input'), Field('textarea'), 'radio_buttons',
        Field('checkboxes', style="background: #FAFAFA"),
        Row(
            Column('text_input_a', 'text_input_b'),
            Column('text_input_c'),
        ),
        FormActions(
            Submit('save_changes', 'Save changes', css_class="btn-primary"),
            Submit('cancel', 'Cancel'),
        ))
Пример #15
0
class TapForm(forms.ModelForm):
    class FlowMeterModelChoiceField(forms.ModelChoiceField):
        def label_from_instance(self, meter):
            if meter.tap:
                return u'{} (connected to {})'.format(meter, meter.tap.name)
            else:
                return unicode(meter)

    class FlowToggleModelChoiceField(forms.ModelChoiceField):
        def label_from_instance(self, toggle):
            if toggle.tap:
                return u'{} (connected to {})'.format(toggle, toggle.tap.name)
            else:
                return unicode(toggle)

    class ThermoSensorModelChoiceField(forms.ModelChoiceField):
        def label_from_instance(self, sensor):
            last_log = sensor.LastLog()
            if last_log:
                return u'{} (Last report: {})'.format(sensor, naturaltime(last_log.time))
            else:
                return unicode(sensor)

    meter = FlowMeterModelChoiceField(queryset=ALL_METERS, required=False,
        empty_label='Not connected.',
        help_text='Tap is routed thorough this flow meter. If unset, reporting is disabled.')

    toggle = FlowToggleModelChoiceField(queryset=ALL_TOGGLES, required=False,
        empty_label='Not connected.',
        help_text='Optional flow toggle (usually a relay/valve) connected to this tap.')

    temperature_sensor = ThermoSensorModelChoiceField(queryset=ALL_THERMOS, required=False,
        empty_label='No sensor.',
        help_text='Optional sensor monitoring the temperature at this tap.')

    class Meta:
        model = models.KegTap
        fields = ('name', 'notes', 'temperature_sensor', 'sort_order')

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

        if self.instance:
            self.fields['meter'].initial = self.instance.current_meter()
            self.fields['toggle'].initial = self.instance.current_toggle()
            self.fields['temperature_sensor'].initial = self.instance.temperature_sensor

    def save(self, commit=True):
        if not commit:
            raise ValueError('TapForm does not support commit=False')
        instance = super(TapForm, self).save(commit=True)
        b = get_kegbot_backend()
        b.connect_meter(instance, self.cleaned_data['meter'])
        b.connect_toggle(instance, self.cleaned_data['toggle'])
        return instance

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.layout = Layout(
        Field('name', css_class='input-xlarge'),
        Field('meter', css_class='input-xlarge'),
        Field('toggle', css_class='input-xlarge'),
        Field('temperature_sensor', css_class='input-xlarge'),
        Field('sort_order', css_class='input-xlarge'),
        Field('notes', css_class='input-block-level', rows='3'),
        FormActions(
            Submit('submit_tap_form', 'Save Settings', css_class='btn-success'),
        )
    )
Пример #16
0
    def __init__(self, *args, **kwargs):
        #global question1, question2
        print("StationDetailForm - init")
        #dir(StationDetailForm.question1)
        #StationDetailForm.question1 = forms.CharField(label = "different question",required = True,)
        #pprint(StationDetailForm.question1)
        #question2 = forms.CharField(label = "Question 2",required = True,)

        print("len(args[0])=" + str(len(args[0])))
        stationQuestions = args[0]
        pprint(stationQuestions)

        self.helper = FormHelper()
        self.helper.form_id = 'id-stationsDataForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'

        self.helper.layout = Layout()

        # first questions - the current situation
        nq = len(stationQuestions["Current-questions"])
        if (nq > 0):
            questionsFieldset = Fieldset(
                '',  # legend of the fieldset
                HTML("""<h3>Your current situation:</h3> """))

            for i in range(nq):
                questionsFieldset.append(
                    HTML("<p>" + stationQuestions["Current-questions"][i] +
                         "</p>"))
                response = stationQuestions["Current-responses"][i]
                if response['type'] == "NUMBER_BETWEEN":
                    valuerange = (response['values'][0]['userEnteredValue'],
                                  response['values'][1]['userEnteredValue'])
                    pprint(valuerange)
                    name = 'integer' + str(i)
                    questionsFieldset.append(name)
                elif response['type'] == "ONE_OF_RANGE":
                    valuesString = response['values'][0]['userEnteredValue']
                    if valuesString == "=YesNo":
                        choices = ["yes", "no"]
                    name = 'choice' + str(i)
                    questionsFieldset.append(name)
                else:
                    pprint(response['type'])
                    name = 'question' + str(i)
                    questionsFieldset.append(name)

            self.helper.layout.append(questionsFieldset)

        # next questions - the planned situation
        if (len(stationQuestions["Planned-questions"]) > 0):
            anotherFieldset = Fieldset(
                '',  # legend of the fieldset
                HTML("""<hr><h3>What you plan to do</h3>"""))
            anotherFieldset.append('question2')
            self.helper.layout.append(anotherFieldset)

        self.helper.layout.append(
            FormActions(
                Button('estimate', 'Estimate'),
                Button('submit', 'Continue'),
            ))
        #for i in range(numQuestions):
        #    txt = 'question'+str(i+1)
        #    self.helper.layout[0].append(txt)

        #self.helper.layout[0]

        self.helper.form_action = 'submit_survey'
        super(StationDetailForm, self).__init__()
Пример #17
0
class ChangeKegForm(forms.Form):
    keg_size = forms.ChoiceField(choices=keg_sizes.CHOICES,
        initial=keg_sizes.HALF_BARREL,
        required=True)

    initial_volume = forms.FloatField(label='Initial Volume', initial=0.0,
        required=False, help_text='Keg\'s Initial Volume')

    beer_name = forms.CharField(required=False)  # legacy
    brewer_name = forms.CharField(required=False)  # legacy

    beverage_name = forms.CharField(label='Beer Name', required=False)
    beverage_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    producer_name = forms.CharField(label='Brewer', required=False)
    producer_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    style_name = forms.CharField(required=True, label='Style',
      help_text='Example: Pale Ale, Stout, etc.')

    helper = FormHelper()
    helper.form_class = 'form-horizontal beer-select'
    helper.layout = Layout(
        Field('beverage_name', css_class='input-xlarge'),
        Field('beverage_id', type='hidden'),
        Field('producer_name', css_class='input-xlarge'),
        Field('producer_id', type='hidden'),
        Field('style_name', css_class='input-xlarge'),
        Field('keg_size', css_class='input-xlarge'),
        Field('initial_volume', css_class='input-volume'),
        FormActions(
            Submit('submit_change_keg_form', 'Activate Keg', css_class='btn-primary'),
        )
    )

    def clean_beverage_name(self):
        beverage_name = self.cleaned_data.get('beverage_name')
        if not beverage_name:
            beverage_name = self.cleaned_data.get('beer_name')
            if not beverage_name:
                raise forms.ValidationError('Must specify a beverage name')
            self.cleaned_data['beverage_name'] = beverage_name
        return beverage_name

    def clean_producer_name(self):
        producer_name = self.cleaned_data.get('producer_name')
        if not producer_name:
            producer_name = self.cleaned_data.get('brewer_name')
            if not producer_name:
                raise forms.ValidationError('Must specify a producer name')
            self.cleaned_data['producer_name'] = producer_name
        return producer_name

    def save(self, tap):
        if not self.is_valid():
            raise ValueError('Form is not valid.')
        b = get_kegbot_backend()

        if tap.is_active():
            b.end_keg(tap.current_keg)

        keg_size = self.cleaned_data.get('keg_size')
        full_volume_ml = self.cleaned_data.get('full_volume_ml')

        if keg_size != 'other':
            full_volume_ml = None
        else:
            full_volume_ml = self.cleaned_data.get('initial_volume')

        # TODO(mikey): Support non-beer beverage types.
        cd = self.cleaned_data
        keg = b.start_keg(tap, beverage_name=cd['beverage_name'], producer_name=cd['producer_name'],
            beverage_type='beer', style_name=cd['style_name'], keg_type=cd['keg_size'],
            full_volume_ml=full_volume_ml)

        if cd.get('description'):
            keg.description = cd['description']
            keg.save()
Пример #18
0
    def __init__(self, *args, **kwargs):
        assert 'instance' not in kwargs

        self._proposal = kwargs.pop('proposal')

        try:
            proposal_evaluation = ProposalEvaluation.objects.get(
                proposal=self._proposal)
            kwargs['instance'] = proposal_evaluation
        except ObjectDoesNotExist:
            pass

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

        self.helper = FormHelper(self)
        self.helper.form_action = reverse('logged-proposal-evaluation-update',
                                          kwargs={'pk': self._proposal.id})

        XDSoftYearMonthDayPickerInput.set_format_to_field(
            self.fields['decision_date'])
        XDSoftYearMonthDayPickerInput.set_format_to_field(
            self.fields['decision_letter_date'])
        self.fields['proposal'].initial = self._proposal
        requested_budget = self._proposal.total_budget()

        self.fields['allocated_budget'] = FlexibleDecimalField(required=False)
        self.fields[
            'allocated_budget'].help_text = f'Requested: {thousands_separator(requested_budget)} CHF'
        self.fields['allocated_budget'].label = 'Allocated budget (CHF)'

        if hasattr(self._proposal, 'proposalevaluation'):
            cancel_button_url = reverse(
                'logged-proposal-evaluation-detail',
                kwargs={'pk': self._proposal.proposalevaluation.id})
            initial_reviewers = self._proposal.reviewer_set.all()
        else:
            cancel_button_url = reverse('logged-proposal-evaluation-add'
                                        ) + f'?proposal={self._proposal.id}'
            initial_reviewers = []

        self.fields['reviewers'] = ReviewerMultipleChoiceField(
            initial=initial_reviewers,
            queryset=Reviewer.objects.filter(calls=self._proposal.call),
            required=True,
            widget=FilteredSelectMultiple(is_stacked=True,
                                          verbose_name='reviewers'),
            help_text=self.Meta.help_texts['reviewers'])

        self.helper.layout = Layout(
            Div(Div('proposal', css_class='col-12'), css_class='row'),
            Div(Div('reviewers', css_class='col-12'), css_class='row'),
            Div(Div('panel_remarks', css_class='col-12'), css_class='row'),
            Div(Div('feedback_to_applicant', css_class='col-12'),
                css_class='row'),
            Div(Div('panel_recommendation', css_class='col-6'),
                Div('allocated_budget', css_class='col-6'),
                css_class='row'),
            Div(Div('board_decision', css_class='col-6'),
                Div('decision_date', css_class='col-6'),
                css_class='row'),
            Div(Div('decision_letter', css_class='col-6'),
                Div('decision_letter_date', css_class='col-6'),
                css_class='row'),
            FormActions(Submit('save', 'Save Evaluation'),
                        cancel_edit_button(cancel_button_url)))
Пример #19
0
class EventForm(forms.Form):
    title = forms.CharField(label='Title', max_length=255)

    location = forms.CharField(label='Location', max_length=255)

    start_time = forms.DateTimeField(
        label='Start Time',
        input_formats=[
            '%m/%d/%Y %I:%M%p',
        ],
    )

    end_time = forms.DateTimeField(label='End Time',
                                   input_formats=[
                                       '%m/%d/%Y %I:%M%p',
                                   ],
                                   required=False)

    description = forms.CharField(label='Description',
                                  max_length=6000,
                                  widget=forms.Textarea,
                                  required=False)

    contact_name = forms.CharField(label='Contact Name',
                                   max_length=255,
                                   required=False)

    student_email = UTEmailField(label='Student Email', max_length=255)

    categories = forms.MultipleChoiceField(
        label='Categories',
        widget=forms.SelectMultiple(
            attrs={'size': len(Category.objects.all())}),
        choices=[(c.title, c.title) for c in Category.objects.all()],
    )

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.layout = Layout(
        Field('title',
              css_class='input-lg form-control',
              placeholder='Enter Event Title'),
        Field('location',
              css_class='form-control',
              placeholder='Enter Location'),
        Field('start_time',
              css_class='form-control',
              placeholder='Enter Start Time'),
        Field('end_time',
              css_class='form-control',
              placeholder='Enter End Time'),
        Field('categories',
              css_class='form-control',
              placeholder='Choose Categories'),
        Field(
            'description',
            css_class='form-control',
            placeholder=
            'Enter an Event Description (you can provide contact info here)'),
        Field('contact_name',
              css_class='form-control',
              placeholder='Enter your name or organization'),
        Field('student_email',
              css_class='form-control',
              placeholder=
              'Enter a valid utexas.edu email address (will be kept private)'),
        FormActions(
            Submit('save_changes',
                   'Create',
                   css_class="btn-primary btn-lg",
                   style="margin-top: 25px"), ))
Пример #20
0
from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Button
from crispy_forms.bootstrap import FormActions

from bootstrap3_datetime.widgets import DateTimePicker

from horses.models import Horse, MedicalRecord, Task, Log

form_actions = FormActions(
    Submit('save_changes', 'Save'),
    Button('cancel',
           'Cancel',
           css_class='btn btn-default',
           onclick='history.go(-1);'),
)


class HorseForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(HorseForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_method = 'post'
        self.helper.form_action = ''
        self.helper.form_class = 'well form-vertical'
        self.helper.layout.append(form_actions)

    class Meta:
        model = Horse
        exclude = ['created', 'modified']
Пример #21
0
    def __init__(self, *args, **kwargs):
        url = kwargs.pop('url', None)
        compra = kwargs.pop('compra', None)

        super(CompraUpdateForm, self).__init__(*args, **kwargs)
        self.fields['base_imponible'].widget.attrs['readonly'] = True
        self.fields['igv'].widget.attrs['readonly'] = True

        codigos_comprobante = ["01", "03", "99"]
        self.fields[
            'tipo_comprobante'].queryset = TipoComprobantePago.objects.filter(
                codigo__in=codigos_comprobante)

        self.fields['fecha_emision'] = DateField(
            input_formats=['%d/%m/%Y'],
            widget=forms.DateInput(attrs={
                'class': 'form-control datetimepicker-input',
                'data-target': '#datetimepicker1'
            },
                                   format='%d/%m/%Y'))
        self.fields['fecha_vencimiento'] = DateField(
            input_formats=['%d/%m/%Y'],
            widget=forms.DateInput(attrs={
                'class': 'form-control datetimepicker-input',
                'data-target': '#datetimepicker1'
            },
                                   format='%d/%m/%Y'))

        # self.fields['fecha_vencimiento'].widget.attrs['readonly'] = True

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_action = url
        self.helper.form_class = 'js-validate form-vertical'

        self.helper.layout = Layout(
            Row(
                Div(Field('proveedor', css_class='input-required'),
                    css_class='col-md-4'),
                Div(Field('tipo_comprobante', css_class='input-required'),
                    css_class='col-md-4'),
                Div(Field('tipo_moneda', css_class='input-required'),
                    css_class='col-md-4'),
            ),
            Row(
                Div(Field('fecha_emision', css_class='input-required'),
                    css_class='col-md-3'),
                Div(Field('fecha_vencimiento', css_class='input-required'),
                    css_class='col-md-3'),
                Div(Field('serie_comprobante', css_class='input-required'),
                    css_class='col-md-2'),
                Div(Field('nro_comprobante', css_class='input-required'),
                    css_class='col-md-4'),
            ),
            Row(
                Div(Field('base_imponible', css_class='input-required'),
                    css_class='col-md-4'),
                Div(Field('igv', css_class='input-required'),
                    css_class='col-md-4'),
                Div(Field('total', css_class='input-required'),
                    css_class='col-md-4'),
            ),
            Row(FormActions(smtSave("Actualizar"), ), css_class="text-center"),
        )
Пример #22
0
    def __init__(self, *args, **kwargs):
        self.create = kwargs.pop('create', None)

        super(EnterpriseForm, self).__init__(*args, **kwargs)
        self.fields[
            'name'].help_text = u'<small class="help-error"></small> %s' % _(
                u' ')
        self.fields[
            'tax_id'].help_text = u'<small class="help-error"></small> %s' % _(
                u' ')

        if self.create:
            self.fields['sede'] = forms.CharField(
                label=capfirst(_(u'Sede')),
                required=True,
                initial='Principal',
                help_text=u'<small class="help-error"></small> %s' % _(u' '),
                widget=forms.TextInput(attrs={
                    'class': 'input-required',
                }),
            )
        else:
            self.fields['sede'] = forms.CharField(widget=forms.HiddenInput(),
                                                  required=False)

        self.fields[
            'logo'].help_text = u'<small class="help-error"></small> %s' % _(
                u'Available formats are JPG, GIF, and PNG.')
        self.fields['solution'].required = True
        self.fields[
            'solution'].help_text = u'<small class="help-error"></small> %s' % _(
                u' ')

        self.helper = FormHelper()
        self.helper.form_id = 'form'
        self.helper.form_class = 'js-validate form-vertical'
        self.helper.layout = Layout(
            TabHolder(
                Tab(
                    _('Enterprise'),
                    Row(
                        Div(Field('tax_id',
                                  css_class='input-required',
                                  autofocus=True),
                            css_class='col-md-6'), ),
                    Row(
                        Div(Field('name', css_class='input-required'),
                            css_class='col-md-6'),
                        Div(Field('type_e', css_class='input-required'),
                            css_class='col-md-6'),
                    ),
                    Row(
                        Div(Field(
                            'solution',
                            css_class='input-required',
                        ),
                            css_class='col-md-6'),
                        Div(Field('sede', ), css_class='col-md-6'),
                    ),
                ),
                Tab(_('Image'), Field('logo', css_class="")),
            ),
            Row(FormActions(
                smtSave(),
                btnCancel(),
                btnReset(),
            ), ),
        )
Пример #23
0
class NewReleaseBranchForm(forms.Form):
    """
    Add new branch to release stream
    """
    action_url = ''
    phases_choices = ()
    langset_choices = ()
    enable_flags_choices = (('track_trans_flag', 'Track Translation'),
                            ('sync_calendar', 'Sync Calendar'),
                            ('notifications_flag', 'Notification'))

    relbranch_name = forms.CharField(
        label='Release Branch Name',
        help_text='Version of the release stream.',
        required=True,
    )
    current_phase = forms.ChoiceField(
        label='Current Phase',
        choices=phases_choices,
        required=True,
        help_text='Phase in which this version/branch is running.')
    lang_set = forms.ChoiceField(
        label="Language Set",
        choices=langset_choices,
        required=True,
        help_text='Language set which should be associated with this branch.')
    calendar_url = forms.URLField(
        label='iCal URL',
        help_text=
        'Release schedule calendar URL. (Prefer translation specific)',
        required=True)
    enable_flags = TextArrayField(
        label='Enable flags',
        widget=forms.CheckboxSelectMultiple,
        choices=enable_flags_choices,
        help_text=
        "Selected tasks will be enabled for this release version/branch.",
        required=False)

    def __init__(self, *args, **kwargs):
        self.phases_choices = kwargs.pop('phases_choices')
        self.langset_choices = kwargs.pop('langset_choices')
        self.action_url = kwargs.pop('action_url')
        super(NewReleaseBranchForm, self).__init__(*args, **kwargs)
        self.fields['current_phase'].choices = self.phases_choices
        self.fields['lang_set'].choices = self.langset_choices
        super(NewReleaseBranchForm, self).full_clean()

    helper = FormHelper()
    helper.form_method = 'POST'
    helper.form_action = action_url
    helper.form_class = 'dynamic-form'
    helper.error_text_inline = True
    helper.form_show_errors = True

    helper.layout = Layout(
        Div(
            Field('relbranch_name',
                  css_class='form-control',
                  onkeyup="showBranchNameSlug()"),
            Field('current_phase', css_class='selectpicker'),
            Field('lang_set', css_class='selectpicker'),
            Field('calendar_url', css_class='form-control'),
            InlineCheckboxes('enable_flags'), HTML("<hr/>"),
            FormActions(Submit('addrelbranch', 'Add Release Branch'),
                        Reset('reset', 'Reset'))))

    def is_valid(self):
        return False if len(self.errors) >= 1 else True
Пример #24
0
    def __init__(self, *args, **kwargs):
        super(SolutionForm, self).__init__(*args, **kwargs)
        '''
        self.fields['name'] = forms.CharField(
            label=capfirst(_(u'name')), required=True,
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['description'] = forms.CharField(
            label=_(u'Description'), required=False,
            widget=forms.Textarea(attrs={'rows': 3, }),
            help_text=u'<small class="help-error"></small> %s' % _(
                u' '),
        )
        self.fields['test_image'] = forms.ImageField(
            label=capfirst(_(u'Test image')), required=False,
            initial='test_images/default.png',
            help_text=u'<small class="help-error"></small> %s' % _(
                u'Available formats are JPG, GIF, and PNG.'),
        )
        '''
        self.fields[
            'name'].help_text = u'<small class="help-error"></small> %s' % _(
                u' ')
        self.fields[
            'description'].help_text = u'<small class="help-error"></small> %s' % _(
                u' ')
        self.fields['description'].widget.attrs = {
            'rows': 3,
        }
        self.fields[
            'test_image'].help_text = u'<small class="help-error"></small> %s' % _(
                u'Available formats are JPG, GIF, and PNG.')
        self.fields[
            'price'].help_text = u'<small class="help-error"></small> %s' % _(
                u' ')

        self.fields['test_date'] = forms.DateTimeField(
            label=_(u'Test date'),
            required=False,
            initial=datetime.now().replace(tzinfo=get_current_timezone()),
            widget=forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S', ),
            input_formats=('%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y', '%d-%m-%y',
                           '%Y-%m-%d', '%Y-%m-%d %H:%M:%S'),
            help_text=u'<small class="help-error"></small> %s' %
            _(u'Some useful help text.'),
        )
        self.helper = FormHelper()
        #self.helper.form_tag = False
        # http://bixly.com/blog/awesome-forms-django-crispy-forms/
        self.helper.form_method = 'post'
        self.helper.form_class = 'js-validate form-vertical'
        #self.helper.form_show_labels = False
        #self.fields['name'].label = False
        self.helper.layout = Layout(
            Row(
                Div(Field('name', css_class='input-required'),
                    css_class='col-md-6'),
                Div(Field('description', css_class=''), css_class='col-md-6'),
            ),
            Row(
                Div(Field('price', css_class='input-numeric mask-num'),
                    css_class='col-md-6'),
                Div(Field('test_date', css_class='input-datex'),
                    css_class='col-md-6'),  # falta validar un input-datetime
            ),
            Row(Div(Field('test_image', css_class=''),
                    css_class='col-md-6'), ),
            Row(FormActions(
                smtSave(),
                btnCancel(),
                btnReset(),
            ), ),
        )
Пример #25
0
class NewPackageForm(forms.Form):
    """
    Add new package to package list
    """
    transplatform_choices = ()
    relstream_choices = ()
    update_stats_choices = (('stats', 'Translation Stats'), )

    package_name = forms.CharField(
        label='Package Name',
        help_text=
        'Package id as-in translation platform. Use hyphen (-) to separate words.',
        required=True,
    )
    upstream_url = forms.URLField(
        label='Upstream URL',
        help_text='Source repository location (Bitbucket, GitHub, Pagure etc).',
        required=True)
    transplatform_slug = forms.ChoiceField(
        label='Translation Platform',
        choices=transplatform_choices,
        help_text='Translation statistics will be fetched from this server.')
    release_streams = TextArrayField(
        label='Release Stream',
        widget=forms.CheckboxSelectMultiple,
        choices=relstream_choices,
        help_text="Translation progress for selected streams will be tracked.")
    update_stats = forms.ChoiceField(
        label='Update details',
        widget=forms.CheckboxSelectMultiple,
        choices=update_stats_choices,
        help_text=
        "Stats fetch would be attempted. <span class='text-warning'>This may take some time!</span>",
        required=False)

    def __init__(self, *args, **kwargs):
        self.transplatform_choices = kwargs.pop('transplatform_choices')
        self.relstream_choices = kwargs.pop('relstream_choices')
        super(NewPackageForm, self).__init__(*args, **kwargs)
        self.fields['transplatform_slug'].choices = self.transplatform_choices
        self.fields['release_streams'].choices = self.relstream_choices
        super(NewPackageForm, self).full_clean()

    helper = FormHelper()
    helper.form_method = 'POST'
    helper.form_action = '/settings/packages/new'
    helper.form_class = 'dynamic-form'
    helper.error_text_inline = True
    helper.form_show_errors = True

    helper.layout = Layout(
        Div(
            Field('package_name',
                  css_class='form-control',
                  onkeyup="showPackageSlug()"),
            Field('upstream_url',
                  css_class='form-control',
                  onkeyup="showUpstreamName()"),
            Field('transplatform_slug',
                  css_class='selectpicker',
                  onchange="showTransplatformId()"),
            InlineCheckboxes('release_streams'),
            InlineCheckboxes('update_stats'), HTML("<hr/>"),
            HTML(
                "<h5 class='text-info'>Servers configured here may be contacted at intervals.</h5>"
            ),
            FormActions(Submit('addPackage', 'Add Package'),
                        Reset('reset', 'Reset'))))

    def is_valid(self):
        return False if len(self.errors) >= 1 else True
Пример #26
0
    def __init__(self,
                 account,
                 domain,
                 creating_user,
                 data=None,
                 *args,
                 **kwargs):
        super(ConfirmExtraUserChargesForm, self).__init__(account,
                                                          domain,
                                                          creating_user,
                                                          data=data,
                                                          *args,
                                                          **kwargs)
        self.fields['confirm_product_agreement'].label = _(
            'I have read and agree to the <a href="%(pa_url)s" target="_blank">'
            'Software Product Subscription Agreement</a>.') % {
                'pa_url': reverse('product_agreement')
            }

        from corehq.apps.users.views.mobile import ListCommCareUsersView
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Billing Administrators"),
                crispy.Field('billing_admins', css_class='input-xxlarge'),
            ),
            crispy.Fieldset(
                _("Basic Information"),
                'company_name',
                'first_name',
                'last_name',
                crispy.Field('emails', css_class='input-xxlarge'),
                'phone_number',
            ),
            crispy.Fieldset(
                _("Mailing Address"),
                'first_line',
                'second_line',
                'city',
                'state_province_region',
                'postal_code',
                crispy.Field('country',
                             css_class="input-large",
                             data_countryname=dict(COUNTRIES).get(
                                 self.current_country, '')),
            ),
            crispy.Field('confirm_product_agreement'),
            FormActions(
                crispy.HTML(
                    '<a href="%(user_list_url)s" class="btn">%(text)s</a>' % {
                        'user_list_url':
                        reverse(ListCommCareUsersView.urlname,
                                args=[self.domain]),
                        'text':
                        _("Back to Mobile Workers List")
                    }),
                StrictButton(
                    _("Confirm Billing Information"),
                    type="submit",
                    css_class='btn btn-primary disabled',
                    disabled="disabled",
                    css_id="submit-button-pa",
                ),
                crispy.HTML(
                    '<p class="help-inline" id="submit-button-help-qa" style="vertical-align: '
                    'top; margin-top: 5px; margin-bottom: 0px;">%s</p>' %
                    _("Please agree to the Product Subscription "
                      "Agreement above before continuing.")),
            ),
        )
class EstablishingForm3(BaseModelForm):
    def __init__(self, *args, **kwargs):
        super(EstablishingForm3, self).__init__(*args, **kwargs)
        self.fields['revenue'].label = "What are your revenue sources?"
        self.fields[
            'monthly_costs'].label = "What are your monthly operating costs (Excel sheets only)?"
        self.fields[
            'annual_costs'].label = "What are your yearly operating costs (Excel sheets only)?"
        self.fields[
            'growth_ambitions'].label = "What are your growth ambitions for the next 24 months?"
        self.fields[
            'milestones'].label = "What are the main milestones you've achieved in the last 6 months?"
        self.fields[
            'total_sales'].label = "What are your total sales in the last 12 months? (Optional)"
        self.fields[
            'do_you_have_auditedbooks'].label = "Do you have audited books for the last 3 years?"
        self.fields[
            'total_capital'].label = "How much capital have you raised since inception?"

        self.fields[
            'expected_capital'].label = "How much capital do you intend to raise?"
        self.fields['capital_type'].label = "What type of capital do you seek?"
        self.fields['capital_use'].label = "What's the capital intended for?"
        self.fields[
            'yr_1_projected_earnings'].label = "What are your projected earnings for the next 3 years?"
        self.fields['yr_2_projected_earnings'].label = ""
        self.fields['yr_3_projected_earnings'].label = ""

    revenue = forms.CharField()

    monthly_costs = forms.FileField(required=False)
    annual_costs = forms.FileField(required=False)
    growth_ambitions = forms.CharField(widget=forms.Textarea())
    milestones = forms.CharField(widget=forms.Textarea())
    do_you_have_auditedbooks = forms.ChoiceField(choices=(('1', "Yes"),
                                                          ('0', "No")),
                                                 widget=forms.RadioSelect,
                                                 required=True)
    total_capital = forms.CharField()
    total_sales = forms.CharField(required=False)
    expected_capital = forms.CharField()
    capital_type = forms.ChoiceField(
        choices=(
            ('1', "Equity"),
            ('2', "Grants"),
            ('3', "Convertible Debt"),
            ('4', "Commercial Debt (Banks)"),
            ('5', "Soft Debt (Friends)"),
        ),
        widget=forms.RadioSelect,
    )
    capital_use = forms.CharField()
    yr_1_projected_earnings = forms.CharField(required=False)
    yr_2_projected_earnings = forms.CharField(required=False)
    yr_3_projected_earnings = forms.CharField(required=False)

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.layout = Layout(
        Field('revenue', css_class='input-length1 form-control text-small'),
        # Field('monthly_cashflow', css_class='file-upload'),
        # Field('income_statement', css_class='file-upload'),
        Field('monthly_costs'),
        Field('annual_costs'),
        Field('growth_ambitions',
              rows="3",
              css_class='input-length1 form-control text-large'),
        Field('milestones',
              rows="3",
              css_class='input-length1 form-control text-large'),
        Field('total_sales',
              css_class='input-length1 form-control text-small'),
        Field('yr_1_projected_earnings',
              css_class='input-length1 form-control text-small down-10',
              placeholder="Year 1"),
        Field('yr_2_projected_earnings',
              css_class='input-length1 form-control text-small down-10',
              placeholder="Year 2"),
        Field('yr_3_projected_earnings',
              css_class='input-length1 form-control text-small down-10',
              placeholder="Year 3"),
        Field('do_you_have_auditedbooks'),
        Field('total_capital',
              css_class='input-length1 form-control text-small'),
        Field('expected_capital',
              css_class='input-length1 form-control text-small'),
        Field('capital_type'),
        Field('capital_use',
              css_class='input-length1 form-control text-small'),
        FormActions(
            Button('Cancel', 'Previous', css_class="cancelBtn btnPrevious"),
            Submit('establishing_form_3',
                   'Finish',
                   css_class="cancelBtn btnNext"),
        ))

    class Meta:
        model = Innovation
        fields = ('revenue', 'monthly_costs', 'annual_costs',
                  'growth_ambitions', 'milestones', 'do_you_have_auditedbooks',
                  'total_capital', 'expected_capital', 'capital_type',
                  'capital_use', 'total_sales', 'yr_1_projected_earnings',
                  'yr_2_projected_earnings', 'yr_3_projected_earnings')
Пример #28
0
def form_actions(more=[], save_label=_('Salvar')):
    return FormActions(Submit('salvar', save_label, css_class='pull-right'),
                       *more)
Пример #29
0
class MessageForm(forms.Form):
    text_input = forms.CharField()
    text_input2 = forms.CharField()

    textarea = forms.CharField(widget=forms.Textarea(), )

    radio_buttons = forms.ChoiceField(
        choices=
        (('option_one',
          "Option one is this and that be sure to include why it's great"),
         ('option_two',
          "Option two can is something else and selecting it will deselect option one"
          )),
        widget=forms.RadioSelect,
        initial='option_two',
    )

    checkboxes = forms.MultipleChoiceField(
        choices=
        (('option_one',
          "Option one is this and that be sure to include why it's great"),
         ('option_two',
          'Option two can also be checked and included in form results'),
         ('option_three',
          'Option three can yes, you guessed it also be checked and included in form results'
          )),
        initial='option_one',
        widget=forms.CheckboxSelectMultiple,
        help_text=
        "<strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.",
    )

    appended_text = forms.CharField(help_text="Here's more help text")

    appended_text2 = forms.CharField(
        help_text="And a bigger appended text field")

    prepended_text = forms.CharField()

    prepended_text_two = forms.CharField()

    multicolon_select = forms.MultipleChoiceField(
        choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')), )

    boolean_field = forms.BooleanField()

    # Bootstrap4
    helper = FormHelper()
    helper.layout = Layout(
        Field('text_input'), Field('text_input2', css_class='input-lg'),
        Field('textarea', rows="3"), 'radio_buttons',
        Field('checkboxes', style="background: #FAFAFA"),
        AppendedText('appended_text', '.00'),
        AppendedText('appended_text2', '.00', css_class='input-lg'),
        PrependedText(
            'prepended_text',
            '<input type="checkbox" checked="checked" value="" id="" name="">',
            active=True), PrependedText('prepended_text_two', '@'),
        'multicolon_select', 'boolean_field',
        FormActions(
            Submit('save_changes', 'Save changes', css_class="btn-primary"),
            Submit('cancel', 'Cancel'),
        ))

    helper.label_class = 'col-lg-4'
    helper.field_class = 'col-lg-8'
Пример #30
0
class DesignOptionsForm(forms.ModelForm):
    class Meta:
        model = DesignModel
        fields = [
            'rho', 'Aoptimality', 'resolution', 'G', 'q', 'I', 'cycles',
            'preruncycles', 'conv_crit', 'HardProb', 'outdes', 'Optimisation'
        ]

    def __init__(self, *args, **kwargs):
        super(DesignOptionsForm, self).__init__(*args, **kwargs)
        self.fields[
            'rho'].label = "The assumed temporal autocorrelation coefficient."
        self.fields[
            'Aoptimality'].label = "Do you want to optimise using A-optimality or D-optimality?"
        #self.fields['Saturation'].label = "We assume that there is saturation in the BOLD-signal: the signal cannot exceed 2 times the height of the HRF.  This avoids that for an ITI going towards 0, the signal goes to infinity."
        self.fields[
            'resolution'].label = "The resolution of the timing of stimuli."
        self.fields[
            'G'].label = "How many designs go from one generation to the next?"
        self.fields['q'].label = "What percentage of the trials gets mutated?"
        self.fields['I'].label = "How many immigrants per generation?"
        self.fields[
            'cycles'].label = "Number of generations (iterations or cycles)."
        self.fields[
            'preruncycles'].label = "Number of generations in the prerun to define the maximum efficiency and detection power."
        self.fields[
            'conv_crit'].label = "Number of stable generations to reach convergence"
        self.fields[
            'HardProb'].label = "Do you want a hard limit on the probabilities? (experimental)"
        self.fields['outdes'].label = 'How many designs do you want to get?'
        self.fields[
            'Optimisation'].label = "Do you want to optimise using the Genetic Algorithm or with random designs?"

    def clean(self):
        cleaned_data = super(DesignOptionsForm, self).clean()
        return cleaned_data

    helper = FormHelper()
    helper.form_method = 'POST'
    helper.field_class = 'col-lg-12'
    helper.label_class = 'col-lg-12'
    helper.layout = Layout(
        Fieldset(
            'Design and optimisation parameters',
            HTML(
                """<p>These parameters are hidden and the default values can be found below.  To change the parameters, fill out the fields you wish to change and click save.</p><br><br>"""
            ),
            Div(Div(Field('rho'), css_class='col-xs-12'),
                Div(Field('Aoptimality'), css_class='col-xs-12'),
                Div(Field('Optimisation'), css_class='col-xs-12'),
                Div(Field('resolution'), css_class='col-xs-12'),
                Div(Field('outdes'), css_class='col-xs-12'),
                Div(Field('HardProb'), css_class='col-xs-4'),
                css_class='row-md-12 col-xs-12')), HTML("<br><br><br>"),
        Fieldset(
            'Genetic algorithm parameters',
            HTML(
                """<p>The following parameters are set for a good flow of the genetic algorithm.</p><br><br>"""
            ),
            Div(Div(Field('G'), css_class='col-xs-12'),
                Div(Field('q'), css_class='col-xs-12'),
                Div(Field('I'), css_class='col-xs-12'),
                Div(Field('cycles'), css_class='col-xs-12'),
                Div(Field('preruncycles'), css_class='col-xs-12'),
                Div(Field('conv_crit'), css_class='col-xs-12'),
                css_class='row-md-12 col-xs-12')),
        HTML("""<br><br><br><br><br>"""),
        FormActions(Submit('Submit', 'Save', css_class='btn-black')),
        HTML("""<br><br><br><br><br>"""))