Exemplo n.º 1
0
    def __init__(self,
                 allow_edit=True,
                 res_short_id=None,
                 element_id=None,
                 element_name=None,
                 *args,
                 **kwargs):

        file_type = kwargs.pop('file_type', False)

        layout = Layout()
        # the order in which the model fields are listed for the FieldSet is the order these
        # fields will be displayed
        layout.append(
            Field('type',
                  id="id_{}_filetype".format('type')
                  if file_type else "id_{}".format('type')))
        form_field_names = [
            'name', 'projection', 'east', 'north', 'northlimit', 'eastlimit',
            'southlimit', 'westlimit', 'units'
        ]
        crispy_form_fields = get_crispy_form_fields(form_field_names,
                                                    file_type=file_type)
        for field in crispy_form_fields:
            layout.append(field)
        kwargs['coverage'] = 'spatial'
        super(CoverageSpatialFormHelper,
              self).__init__(allow_edit, res_short_id, element_id,
                             element_name, layout, *args, **kwargs)
Exemplo n.º 2
0
    def layout(self):
        if settings.TARGET_PERMISSIONS_ONLY:
            groups = Div()
        else:
            groups = Row('groups')

        # Add filters to layout
        filter_layout = Layout(
            Row(
                Column(HTML('Exposure Time')),
                Column(HTML('No. of Exposures')),
                Column(HTML('Block No.')),
            ))
        for filter_name in self.filters:
            filter_layout.append(Row(PrependedText(filter_name, filter_name)))
        return Div(Div(filter_layout, css_class='col-md-6'),
                   Div(Div(Row('max_airmass'),
                           Row(PrependedText('min_lunar_distance', '>')),
                           Row('instrument_type'),
                           Row('proposal'),
                           Row('observation_mode'),
                           Row('ipp_value'),
                           Row(AppendedText('reminder', 'days')),
                           css_class='form-row'),
                       Div(Row('guider_mode'),
                           Row('exposure_mode'),
                           Row('diffuser_g_position'),
                           Row('diffuser_r_position'),
                           Row('diffuser_i_position'),
                           Row('diffuser_z_position'),
                           css_class='form-row',
                           css_id='muscat-div'),
                       Div(groups, css_class='form-row'),
                       css_class='col-md-6'),
                   css_class='form-row')
Exemplo n.º 3
0
    def layout(self):
        if settings.TARGET_PERMISSIONS_ONLY:
            groups = Div()
        else:
            groups = Row('groups')

        # Add filters to layout
        filter_layout = Layout(
            Row(
                Column(HTML('Exposure Time')),
                Column(HTML('No. of Exposures')),
                Column(HTML('Block No.')),
            ))
        for filter_name in self.filters:
            filter_layout.append(
                Row(MultiWidgetField(filter_name, attrs={'min': 0})))

        return Div(Div(filter_layout, css_class='col-md-6'),
                   Div(Row('max_airmass'),
                       Row(PrependedText('min_lunar_distance', '>')),
                       Row('instrument_type'),
                       Row('proposal'),
                       Row('observation_mode'),
                       Row('ipp_value'),
                       groups,
                       css_class='col-md-6'),
                   css_class='form-row')
Exemplo n.º 4
0
 def test_append_layout_object(self):
     layout = Layout(
         Div('email')
     )
     layout.append('password1')
     self.assertTrue(isinstance(layout[0], Div))
     self.assertTrue(isinstance(layout[0][0], basestring))
     self.assertTrue(isinstance(layout[1], basestring))
Exemplo n.º 5
0
 def test__getattr__append_layout_object(self):
     layout = Layout(
         Div('email')
     )
     layout.append('password1')
     self.assertTrue(isinstance(layout[0], Div))
     self.assertTrue(isinstance(layout[0][0], string_types))
     self.assertTrue(isinstance(layout[1], string_types))
Exemplo n.º 6
0
def test__getattr__append_layout_object():
    layout = Layout(
        Div('email')
    )
    layout.append('password1')
    assert isinstance(layout[0], Div)
    assert isinstance(layout[0][0], string_types)
    assert isinstance(layout[1], string_types)
Exemplo n.º 7
0
 def test_append_layout_object(self):
     layout = Layout(
         Div('email')
     )
     layout.append('password1')
     self.assertTrue(isinstance(layout[0], Div))
     self.assertTrue(isinstance(layout[0][0], basestring))
     self.assertTrue(isinstance(layout[1], basestring))
Exemplo n.º 8
0
def choose_or_create(*args, **kwargs):
    layout = Layout()

    fieldname = kwargs.get('fieldname', 'organization')
    data_selecturl = kwargs.get('data_selecturl', '/selecttwo/nhdb/project/name/icontains')
    data_modalurl =  kwargs.get('data_modalurl', '/nhdb/form/organization/main/')
    layout.append(Field(fieldname ,data_selecturl = data_selecturl, placeholder=fieldname, style='width:70%;'))
    layout.append(Button('Add','Add a new %s'%(fieldname),  style='width:25%;', data_modalurl = data_modalurl))
    return layout
Exemplo n.º 9
0
    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)
        initial = kwargs.pop('initial', {})
        fields = OrderedDict()
        layout = Layout()
        property_group = PropertyGroup.objects.get(name=self.instance.kind.name)
        values = ComponentPropertyValue.objects.filter(component=self.instance)
        values_map = dict([(v.property_id, v) for v in values])
        for prop in property_group.properties.all():
            field_name = prop.name.replace('.', '_')
            field_kwargs = {
                'label': prop.title,
                'required': prop.required,
            }
            if field_name not in initial and prop.pk in values_map:
                if prop.is_select_field:
                    initial[field_name] = values_map[prop.pk].option_id
                else:
                    initial[field_name] = values_map[prop.pk].get_value()

            if prop.is_text_field:
                field_class = forms.CharField
            elif prop.is_number_field:
                field_class = forms.IntegerField
            elif prop.is_select_field:
                field_class = forms.ChoiceField
                field_kwargs['choices'] = [
                    (o.id, o.name)
                    for o in prop.options.all()
                ]
            else:
                continue
            fields[field_name] = field_class(**field_kwargs)
            layout.append(
                Div(
                    Div(field_name, css_class='col-xs-12'),
                    css_class='row-fluid'
                )
            )
        layout.append(
            FormActions(
                Submit('save_changes', _('Save changes'), css_class="btn-primary"),
                Submit('cancel', 'Cancel'),
            )
        )
        super(ComponentPropertiesForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.form_tag = False
        self.helper.layout = layout
        self.fields = fields
        self.initial = initial
Exemplo n.º 10
0
    def _get_form_layout(self, items):

        # Collect them
        layout = Layout()

        # Get all the not groups
        for item in items:

            # Check type
            if item.type == 'group':

                # Add the fieldset
                layout.append(self._get_form_fieldset(item.item, item.text))

            elif item.type == 'display':

                # Add the text
                layout.append(HTML('<p>{}</p>'.format(item.text)))


            elif item.type == 'question' and item.item:

                # Add the linkId
                layout.append(item.linkId)

                # Check for groups
                for subitem in item.item:

                    # If group...
                    if subitem.type == 'group':

                        # Set attributes
                        attrs = {
                            'data_parent': item.linkId,
                            'data_detached': "true",
                            'data_required': "true" if item.required else "false",
                            'id': 'id_{}_{}'.format(item.linkId, subitem.linkId)
                        }
                        for enable_when in subitem.enableWhen:
                            attrs['data_enabled-when'] = '{}={}'.format(enable_when.question, enable_when.answerString)

                        # Add the fieldset
                        layout.append(self._get_form_fieldset(subitem.item, "", **attrs))

            else:

                # Add the linkId
                layout.append(item.linkId)

        return layout
Exemplo n.º 11
0
class DeleteFormHelper(FormHelper):

    def __init__(self, instance, url=None, css_class='btn-sm btn-warning', buttontext='Delete', alert=None):

        errormessage = '<div class="alert alert-danger" role="alert"><strong>Please confirm: </strong> You are about to remove <strong>{}</strong> from the database</div>'

        app, mod, pk = instance._meta.app_label, instance._meta.model_name, instance.pk
        submit_url = url or '/rest/{}/{}/{}/'.format(app, mod, pk)

        if not instance.pk:
            raise TypeError('Cannot create a DeleteForm for an uninitialised object: {}'.format(instance))

        # The URL can be specified manually but if not given, is automatically tried from '/rest/app/model/pk/'

        super(DeleteFormHelper, self).__init__()
        self.attrs = {'action': '/suggest/suggest/'}
        self.form_method = 'POST'
        self.layout = Layout(
            Hidden('_method', 'DELETE'),
            Hidden('_url', submit_url),
            Hidden('_action', 'DM'),
            Hidden('_description', u'Remove {} from the database'.format(instance)),
            Hidden('_affected_instance_primary', '{}_{} {}'.format(app, mod, pk)),
            # FormActions(
            #     Submit('__action', buttontext, css_class=css_class+' hidden'),
            # ))
        )
        if alert is True:
            try:
                self.layout.append(
                HTML(errormessage.format(instance))
                )
            except:
                self.layout.append(
                HTML(errormessage.format('an object'))
                )
        elif isinstance(alert, basestring):
            try:
                self.layout.append(
                HTML(errormessage.format(alert))
                )
            except:
                self.layout.append(
                HTML(errormessage.format('an object'))
                )
        elif alert:
            self.layout.append(
            HTML(errormessage.format(alert))
            )
Exemplo n.º 12
0
    def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
                 *args, **kwargs):
        """Render layout for CoverageSpatial form."""
        file_type = kwargs.pop('file_type', False)

        layout = Layout()
        # the order in which the model fields are listed for the FieldSet is the order these
        # fields will be displayed
        layout.append(Field('type', id="id_{}_filetype".format('type') if file_type else
                            "id_{}".format('type')))
        form_field_names = ['name', 'projection', 'east', 'north', 'northlimit', 'eastlimit',
                            'southlimit', 'westlimit', 'units']
        crispy_form_fields = get_crispy_form_fields(form_field_names, file_type=file_type)
        for field in crispy_form_fields:
            layout.append(field)
        kwargs['coverage'] = 'spatial'
        super(CoverageSpatialFormHelper, self).__init__(allow_edit, res_short_id, element_id,
                                                        element_name, layout,  *args, **kwargs)
Exemplo n.º 13
0
    def _get_form_layout(self, items):

        # Collect them
        layout = Layout()

        # Get all the not groups
        for item in items:

            # Check type
            if item.type == 'group':

                # Add the fieldset
                layout.append(self._get_form_fieldset(item.item, item.text))

            elif item.type == 'display':

                # Add the text
                layout.append(HTML('<p>{}</p>'.format(item.text)))


            elif item.type in ['question', 'boolean'] and item.item:

                # Add the linkId
                layout.append(item.linkId)

                # Check for groups
                for subitem in item.item:

                    # If group...
                    if subitem.type == 'group':

                        # Set attributes
                        attrs = self._get_form_layout_group_attributes(item, subitem)

                        # Add the fieldset
                        layout.append(self._get_form_fieldset(subitem.item, "", **attrs))

            else:

                # Add the linkId
                layout.append(item.linkId)

        return layout
Exemplo n.º 14
0
    def init_subreddits_list(self, subreddits):
        layout = Layout()
        self.helper.layout = layout

        for subreddit in subreddits:
            flair_css_field_id = self.get_css_field_name(subreddit.id)
            flair_text_field_id = self.get_text_field_name(subreddit.id)
            self.fields[flair_css_field_id] = CharField(required=False)
            self.fields[flair_text_field_id] = CharField(required=False)
            fieldset = Fieldset(
                '/r/{0}:'.format(subreddit.name),
                Field(flair_css_field_id, placeholder='Flair CSS'),
                Field(flair_text_field_id, placeholder='Flair text'),
            )
            layout.append(fieldset)
        layout.append(
            FormActions(
                Submit('save', 'Save', css_class='btn-primary'),
                Button('cancel', 'Cancel'),
            )
        )
Exemplo n.º 15
0
    def _get_form_layout(self, items):

        # Collect them
        layout = Layout()

        # Get all the not groups
        for item in items:

            # Check type
            if item.type == 'group':

                # Add the fieldset
                layout.append(self._get_form_fieldset(item.item, item.text))

            elif item.type == 'display':

                # Add the text
                layout.append(HTML('<p>{}</p>'.format(item.text)))

            else:

                # Add the linkId
                layout.append(item.linkId)

        return layout
Exemplo n.º 16
0
def get_user_formLayout(_fkeys, report_settings, form_inst):
    layout = Layout(
        # PanelContainer(
        # #     Div(
        #         _('filters'),
        Div(
            # Div(StackedField('doc_date'), css_class='col-sm-3'),
            Div(StackedField2('from_doc_date',
                              css_class='form-control dateinput'),
                css_class='col-sm-6'),
            Div(StackedField2('to_doc_date',
                              css_class='form-control dateinput'),
                css_class='col-sm-6'),
            css_class='row raReportDateRange'),
        Div(css_class="mt-20", style='margin-top:20px'))

    # We add foreign keys to 3rd item in the layout object (count top level only) , which is the
    # fieldset containing doc_date , from_doc_date & to_doc_date
    entry_point = layout.fields[1]
    if report_settings.get('can_edit_matrix_entities', False):
        if hasattr(form_inst, 'cleaned_data'):
            if form_inst.cleaned_data['matrix'] != '':
                entry_point.append(
                    Row(Div('matrix_entities', css_class='col-sm-9'),
                        Div('matrix_show_other', css_class='col-sm-3'),
                        css_class='matrixField'))

    for k in _fkeys:
        # if k[:-3] in report_settings['fkey_visibility'] and k[:-3] != report_settings['matrix']:
        if k[:-3] != report_settings['matrix']:
            entry_point.append(Field(k))

    if report_settings.get('can_edit_primary_index', False):
        layout.append(Column(Field('group_by'), css_class='col-sm-3'))
    if report_settings.get('can_edit_secondary_index', False):
        layout.append(Column(Field('aggregate_on'), css_class='col-sm-3'))
    if report_settings.get('can_edit_time_series_pattern', False):
        layout.append(
            Column(Field('group_time_series_pattern'), css_class='col-sm-3'))
    if report_settings.get('can_edit_doc_types', False):
        layout.append(Column(Field('doc_types'), css_class='col-sm-3'))

    return layout
Exemplo n.º 17
0
class DeepFriedForm(LayoutObject):
    '''Custom crispy layout object. 
    This object:
     1) Replaces all placeholder text with the label text.
     2) Removes the help text and labels.
     3) Sets the submit button text
     4) Sets the cancel url and text (if available)
     
    Example::
    
        DeepFriedForm(submit_text="Save", cancel_url="/home/", cancel_text="Cancel")
        
    '''
    def __init__(self, *fields, **kwargs):
        # kwargs.pop verifies valid parameters, and specifies a default value
        self.render_buttons = kwargs.pop('render_buttons', True)
        self.submit_text = kwargs.pop('submit_text', 'Submit')
        self.cancel_url = kwargs.pop('cancel_url', None)
        self.cancel_text = kwargs.pop('cancel_text', None)
        self.render_delete_buttons = kwargs.pop('render_delete_buttons', False)
        self.delete_text = kwargs.pop('delete_text', None)
        self.layout_object = Layout()

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
        # layout_object = Layout()
        for field_name, field in form.fields.items():
            if (field_name == 'sequence'):
                '''Add helper text for sequence field in blocks
                '''
                self.layout_object.append(
                    Field(
                        HTML('''<small class="helper-text helper-text-block">
                            You may specify a sequence for your block. If left
                            blank, Aion will order blocks in alpha-numeric 
                            order based on the block name.
                            </small>''')))

            if (isinstance(field, forms.DateField)):

                self.layout_object.append(
                    Field(
                        field_name,
                        template="reservations/deep_fried/deep_fried_date.html"
                    ))

            elif (isinstance(field, forms.BooleanField)):
                if field_name == 'enabled':
                    self.layout_object.append(
                        Field(
                            field_name,
                            template=
                            "reservations/deep_fried/deep_fried_switch_enable.html"
                        ))
                else:
                    self.layout_object.append(
                        Field(
                            field_name,
                            template=
                            "reservations/deep_fried/deep_fried_switch.html"))
            elif (isinstance(field, forms.MultipleChoiceField)):
                self.layout_object.append(
                    Field(
                        field_name,
                        template=
                        "reservations/deep_fried/deep_fried_multi_switch.html")
                )
            else:
                self.layout_object.append(
                    Field(
                        field_name,
                        placeholder=field.label,  # Set placeholder to label
                        aria_label=field.label))

            field.help_text = None  # surpress help_text

        if self.render_buttons:

            if self.cancel_url is None or self.cancel_text is None:
                self.layout_object.append(
                    ButtonHolder(Submit('submit',
                                        self.submit_text,
                                        css_class='btn-dark-gray'),
                                 css_class="btn-group d-flex"))
            else:
                self.layout_object.append(
                    ButtonHolder(
                        Submit('submit',
                               self.submit_text,
                               css_class='btn-dark-gray'),
                        HTML(
                            f"""<a class="btn btn-secondary" href="{self.cancel_url}">{self.cancel_text}</a>"""
                        ),
                        css_class="btn-group d-flex"))

        if self.render_delete_buttons:
            # todo: Fix this button so the text isn't always "RESOURCE"
            self.layout_object.append(
                ButtonHolder(HTML(
                    f'''<button type="submit" value="submit" class="btn btn-primary">
                    <i class="fas fa-exclamation-triangle"></i>&nbsp;{self.delete_text}&nbsp;<i class="fas fa-exclamation-triangle"></i>
                    </button>'''),
                             css_class="btn-group d-flex"))

        return self.layout_object.render(form, form_style, context)
Exemplo n.º 18
0
class FormHelper(CrispyFormHelper, WFormHelper):
    """
    Extended WFormHelper based on crispy WFormHelper,
    Dynamic form fields according to inputs types and parameters
    """

    # TODO Created dedicated field for (copy_paste field)

    def __init__(self, form=None, **kwargs):
        form_tag = kwargs.pop('form_tag', True)
        form_class = kwargs.pop('form_class', 'form-horizontal')
        label_class = kwargs.pop('label_class', 'col-lg-4')
        field_class = kwargs.pop('field_class', 'col-lg-8 text-left')
        template_pack = kwargs.pop('template_pack',
                                   waves_settings.TEMPLATE_PACK)
        self.form_obj = form
        super(FormHelper, self).__init__(form)
        self.form_tag = form_tag
        self.form_class = form_class
        self.label_class = label_class
        self.field_class = field_class
        self.render_unmentioned_fields = False
        self.layout = Layout()
        self.template_pack = template_pack

    def set_layout(self, service_input, form=None):
        """
        Setup crispy form for a submission
        """
        css_class = ""
        field_id = "id_" + service_input.api_name
        dependent_on = ""
        dependent_4_value = ""
        has_sample = isinstance(
            service_input,
            FileInput) and service_input.input_samples.count() > 0
        has_dependent = service_input.dependents_inputs.count() > 0

        if has_dependent or has_sample:
            css_class = "has_dependent"

        field_dict = dict(
            css_class=css_class,
            id=field_id,
            title=service_input.help_text,
        )
        wrapper = dict()
        if service_input.parent is not None and not isinstance(
                service_input, FileInputSample):
            field_id += '_' + service_input.parent.api_name + '_' + service_input.api_name
            dependent_on = service_input.parent.api_name
            dependent_4_value = service_input.when_value
            field_dict.update(
                dict(dependent_on=service_input.parent.api_name,
                     dependent_4_value=str(service_input.when_value)))
            when_value = self.form_obj.data.get(service_input.parent.api_name,
                                                service_input.parent.default)
            if when_value is None:
                when_value = False
            hide_dep = service_input.when_value_python != when_value
            if when_value is not None:
                if type(service_input.when_value_python) is int:
                    hide_dep = (service_input.when_value_python !=
                                int(when_value))
                    print "hide dep", hide_dep, when_value, service_input.when_value_python
                elif type(service_input.when_value_python) is Decimal:
                    hide_dep = (service_input.when_value_python != Decimal(
                        when_value.strip(' "')))
                elif type(service_input.when_value_python) is bool:
                    bool_value = str(when_value).lower() in ("yes", "true",
                                                             "t", "1")
                    hide_dep = (service_input.when_value_python != bool_value)

            if hide_dep:
                wrapper = dict(wrapper_class="hid_dep_parameter",
                               disabled="disabled")
            else:
                wrapper = dict(wrapper_class="dis_dep_parameter")
        # file inputs
        if isinstance(service_input, FileInput):
            all_sample = []
            if has_sample:
                for sample in service_input.input_samples.all():
                    all_sample.append(
                        Field('sp_' + service_input.api_name + '_' +
                              str(sample.pk),
                              dependent_on=service_input.api_name,
                              dependent_4_value=dependent_4_value,
                              **wrapper))
            field_dict.update(wrapper)
            input_field = Div(Field(service_input.api_name, **field_dict),
                              *all_sample)

            if service_input.allow_copy_paste:
                cp_input_field = Field('cp_' + service_input.api_name,
                                       css_id='id_' + 'cp_' +
                                       service_input.api_name)
                tab_input = bootstrap.Tab("File Upload",
                                          input_field,
                                          css_id='tab_' +
                                          service_input.api_name)
                self.layout.append(
                    Div(bootstrap.TabHolder(
                        tab_input,
                        bootstrap.Tab(
                            "Copy/paste content",
                            cp_input_field,
                            css_class='copypaste',
                            css_id='tab_cp_' + service_input.api_name,
                            dependent_on=dependent_on,
                            dependent_4_value=dependent_4_value,
                        ),
                        css_id='tab_holder_' + service_input.api_name,
                    ),
                        id='tab_pane_' + service_input.api_name,
                        css_class=wrapper['wrapper_class'],
                        dependent_on=dependent_on,
                        dependent_4_value=dependent_4_value))

            else:
                self.layout.append(input_field)
        elif not isinstance(service_input, FileInputSample):
            field_dict.update(wrapper)
            input_field = Field(service_input.api_name, **field_dict)
            self.layout.append(input_field)
        if isinstance(
                service_input, FileInput
        ) and not service_input.allow_copy_paste and service_input.input_samples.count(
        ) > 0:
            for sample in service_input.input_samples.all():
                self.layout.append(
                    Field('sp_' + service_input.api_name + '_' +
                          str(sample.pk)))

    def init_layout(self, fields):
        l_fields = []
        for field in fields:
            l_fields.append(Field(field))
        self.layout = Layout()
        self.layout.extend(l_fields)
        return self.layout

    def end_layout(self):
        self.layout.extend([
            HTML('<HR/>'),
            bootstrap.FormActions(Reset('reset', 'Reset form'),
                                  Submit('save', 'Submit a job'))
        ])
Exemplo n.º 19
0
class UserTicketForm(forms.ModelForm):

    gluu_server_version = forms.ChoiceField(
        label=_('Gluu Server Version'),
        choices=constants.GLUU_SERVER_VERSION
    )
    gluu_server_version_comments = forms.CharField(
        label=_('Gluu Server Version'),
        required=False
    )
    product = forms.ChoiceField(
        label=_('Select Product'),
        choices=constants.PRODUCT,
        required=False
    )
    product_version= forms.ChoiceField(
        label=_('Version'),
        choices=constants.Product_Version,
        required=False
    )

    os_version = forms.ChoiceField(
        label=_('Operating System'),
        choices=constants.OS_VERSION
    )

    os_version_name = forms.FloatField(
        label=_('OS Version')
    )

    product_os_version = forms.ChoiceField(
        label =_('Operating System'),
        choices = constants.PRODUCT_OS_VERSION,
        required=False
    )
    product_os_version_name =  forms.FloatField(
        label = _('OS Version'),
        required=False
    )

    ios_version_name = forms.FloatField(
        label = _('iOS Version'),
        required=False
    )

    set_default_product = forms.BooleanField(
        label=_('Set as Default (Static Text)'),
        required=False,

    )

    # set_default_gluu = forms.BooleanField(
    #     label=_('Set as Default'),
    #     required = False
    # )

    description = forms.CharField(
        widget=forms.Textarea,
        help_text=(
            'This field supports <a target="_blank" href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet">markdown formatting.</a>'
        )
    )
    # description_copy = forms.CharField(
    #     widget=AdminPagedownWidget()
    # )
    ticket_category = forms.ChoiceField(
        label=_('Issue Category'),
        choices=constants.ISSUE_CATEGORY,
        required= False
    )

    classification_layout = Layout(
        Div(
            Div(
                Field('gluu_server_version', wrapper_class='col-md-4', css_class='gluu_server_version'),
                Field('gluu_server_version_comments', wrapper_class='col-md-3 hidden',  css_class='gluu_server_version_comments'),
                Field('os_version',wrapper_class='col-md-4 ', css_class="os_version "),
                Field('os_version_name',wrapper_class='col-md-4 os_version_icon', placeholder="Which OS are you using?", css_class="os_version_name "),
                css_class='gluu_layout_div'
            ),
            Div(
               HTML('<div class="col-md-6 add-product ">'),
               StrictButton('Add Product',css_class='add_product_btn'),
               HTML('</div>'),
               # Field('set_default_gluu',  css_class='div_set_default '),
               css_class= 'default_product_div'
        ),
            css_class='main_gluu_div'
        ),


    )

    product_layout= Layout(
         Div(
             Div(
                Field('product',wrapper_class='col-md-3 hidden' , css_class="product"),
                Field('product_version',wrapper_class='col-md-3 ', css_class="product_version "),
                Field('product_os_version',wrapper_class='col-md-3 ', css_class="product_os_version "),
                Field('product_os_version_name',wrapper_class='col-md-2  os_version_icon ', placeholder="os version", css_class="product_os_version_name"),
                Field('ios_version_name',wrapper_class='col-md-1 hidden os_version_icon', placeholder="ios version", css_class="ios_version_name"),
                HTML('<div class="col-md-1 remove"><a class="delete_product_row hidden" href="javascript:void(0);"></a></div>'),
                Field('set_default_product',css_class='div_set_default', wrapper_class='hidden'),
                css_class='product_layout_div'

             ),


             css_class= 'main_product_div layout_sec hidden'
         ),


    )
    description_layout = Layout(
        Div(
            Field(
                'title',
                placeholder='Ticket title',wrapper_class='col-md-12'
            ),

        css_class= 'layout_sec'
        ),
        Div(
            Field(
                'description',wrapper_class='col-md-12',
                placeholder='Ticket description.. please include enough ' +
                'information for someone to reproduce your issue, ' +
                'including all relevant logs.',
                # data_uk_htmleditor='{mode:\'tab\',markdown:true}'
            ),
        css_class= 'layout_sec'
        )
    )

    category_layout = Layout(
        Div(
            Field('issue_type',wrapper_class='col-md-6'),
            Field('ticket_category',wrapper_class='col-md-6'),
        css_class= 'layout_sec'
        ),
    )




    additional_layout = Layout(
        Div(
            PrependedText(
                'send_copy',
                '<span class="glyphicon glyphicon-envelope"></span>',
                placeholder='Separate emails with commas'
            ),
            Field('is_private'),
            css_class= 'layout_sec'
        ),
        Div(
            PrependedText(
                'link_url',
                '<span class="glyphicon glyphicon-link"></span>',
                placeholder='URL to download/view ticket info'
            ),
            css_class= 'layout_sec'
        ),

    )

    button_layout = Div(
        FormActions(
            Submit('save', 'Submit'),
            HTML('<a class="btn btn-default" href="{% url \'home\'%}" id="cancelButton">Cancel</a>')
        ),
        css_class= 'layout_sec'
    )

    uploaded_products_layout = Layout()


    class Meta:

        model = Ticket
        error_css_class = 'error_form'
        fields = ('product','product_version','product_os_version','product_os_version_name','ios_version_name','gluu_server_version','gluu_server_version_comments', 'os_version','os_version_name','title', 'description', 'ticket_category', 'link_url',
                  'send_copy')

    def __init__(self, user='******', *args, **kwargs):

        super(UserTicketForm, self).__init__(*args, **kwargs)
        self.uploaded_products_layout = Layout()

        # if user:
        #     data = get_last_ticket_data(user)
        #     if data:
        #         if data[0] != "N/A":
        #             self.fields['gluu_server_version'].initial = data[0]
        #         if data[1] != None:
        #             self.fields['os_version'].initial = data[1]
        #         if data[2] != "":
        #             self.fields['os_version_name'].initial = data[2]
        # data = None
        if user:
            data = get_last_ticket_data(user)

        if data:
            self.fields['gluu_server_version'].initial = data[0] if data[0] != "N/A" else ""
            self.fields['os_version'].initial = data[1] if data[1] != None else ""
            self.fields['os_version_name'].initial = data[2] if data[2] != "" else 0
            self.fields['gluu_server_version_comments'].initial = data[3] if data[3] != "" else 0
        self.fields['send_copy'].label = "CC Colleagues"
        self.fields['title'].label = "Subject"
        self.button_layout[0][0] = Submit('save', 'Submit')
        self.button_layout[0][1] = HTML(
            '<a class="btn btn-danger" href="{% url \'home\'%}" id="cancelButton">Cancel</a>')

        if self.instance.id:
            self.button_layout[0][0] = Submit('save', 'Save')
            self.button_layout[0][1] = HTML(
                '<a class="btn btn-danger" href="{}" id="cancelButton">Cancel</a>'.format(
                    generate_ticket_link(self.instance)))
            if self.instance.product_ticket_id.all():

                for ticket in self.instance.product_ticket_id.all():
                    if ticket.ios_version_name:
                        html= HTML('''
                            <div class="product_layout_div"> <div id="div_id_product" class="form-group col-md-3 for-margin"> <label for="id_product" class="control-label  requiredField">
                                        Select Product<span class="star">*</span> </label> {} </div> <div id="div_id_product_version" class="form-group col-md-2 for-margin"> <label for="id_product_version" class="control-label  requiredField">
                                        Product Version<span class="star">*</span> </label> {} </div> <div id="div_id_product_os_version" class="form-group col-md-2 for-margin"> <label for="id_product_os_version" class="control-label  requiredField">
                                        Operating System<span class="star">*</span> </label> {} </div> <div id="div_id_product_os_version_name" style="width:128px;" class="form-group col-md-1 for-margin os_version_icon"> <label for="id_product_os_version_name" class="control-label  requiredField">
                                        Android Version<span class="star">*</span></label> <div class="controls "> <input class="numberinput form-control product_os_version_name" id="id_product_os_version_name" name="product_os_version_name" value={} step="any" type="number"> </div></div><div id="div_id_ios_version_name" class="form-group col-md-1 os_version_icon fadeIn animated" style="width:100px;"> <label for="id_ios_version_name" class="control-label ">
                                        iOS Version</label> <div class="controls "> <input class="ios_version_name numberinput form-control" value={} id="id_ios_version_name" name="ios_version_name" step="any" type="number"> </div> </div>
                                        <div class="col-md-1 remove"><a class="delete_product_row" href="javascript:void(0);"></a></div></div>
                        '''.format(product_select_list(ticket.product),product_version_select_list(ticket.product_version),product_os_version_select_list(ticket.product_os_version),ticket.product_os_version_name,ticket.ios_version_name))
                    else:
                        html = HTML('''
                            <div class="product_layout_div"> <div id="div_id_product" class="form-group col-md-3 for-margin"> <label for="id_product" class="control-label  requiredField">
                                        Select Product<span class="star">*</span> </label> {} </div> <div id="div_id_product_version" class="form-group col-md-3 for-margin"> <label for="id_product_version" class="control-label  requiredField">
                                        Product Version<span class="star">*</span> </label> {} </div> <div id="div_id_product_os_version" class="form-group col-md-3 for-margin"> <label for="id_product_os_version" class="control-label  requiredField">
                                        Operating System<span class="star">*</span> </label> {} </div> <div id="div_id_product_os_version_name" class="form-group col-md-2 for-margin os_version_icon"> <label for="id_product_os_version_name" class="control-label  requiredField">
                                        OS Version<span class="star">*</span></label> <div class="controls "> <input class="numberinput form-control product_os_version_name" id="id_product_os_version_name" name="product_os_version_name" value={} step="any" type="number"> </div></div><div id="div_id_ios_version_name" class="form-group col-md-1 os_version_icon hidden fadeIn animated" style="width:100px;"> <label for="id_ios_version_name" class="control-label ">
                                        iOS Version</label> <div class="controls "> <input class="ios_version_name numberinput form-control"  id="id_ios_version_name" name="ios_version_name" step="any" type="number"> </div> </div>
                                        <div class="col-md-1 remove"><a class="delete_product_row" href="javascript:void(0);"></a></div></div>
                        '''.format(product_select_list(ticket.product),product_version_select_list(ticket.product_version),product_os_version_select_list(ticket.product_os_version),ticket.product_os_version_name))

                    self.uploaded_products_layout.append(
                        html
                    )
            # if self.instance.ticket_id.all():
            #     for ticket in self.instance.ticket_id.all():
            #         self.uploaded_classification_layout.append(
            #             HTML('''
            #                 <div class="gluu_layout_div"> <div id="div_id_gluu_server_version" class="form-group col-md-4"> <label for="id_gluu_server_version" class="control-label  requiredField">
            #                 Gluu Server Version<span class="star">*</span> </label> {} </div> <div id="div_id_os_version" class="form-group col-md-4"> <label for="id_os_version" class="control-label  requiredField">
            #                 Operating System<span class="star">*</span> </label> {} </div> <div id="div_id_os_version_name" class="form-group col-md-3 os_version_icon"> <label for="id_os_version_name" class="control-label  requiredField">
            #                 OS Version<span class="star">*</span> </label> <div class="controls "> <input class="numberinput form-control os_version_name" id="id_os_version_name" name="os_version_name" value={} step="any" type="number"> </div> </div>
            #                 <div class="col-md-1 remove"><a class="delete_gluu_row" href="javascript:void(0);"></a></div></div>
            #             '''.format(gluu_server_version_select_list (ticket.gluu_server_version),gluu_os_version_list(ticket.os_version),ticket.os_version_name)
            #                 )
            #         )

        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal ticket_form'
        self.helper.help_text_inline = True
        self.helper.layout = Layout(
            # self.uploaded_classification_layout,
            self.classification_layout,
            self.uploaded_products_layout,
            self.product_layout,
            self.description_layout,
            self.category_layout,
            self.additional_layout,
            self.button_layout
        )


    def clean_ticket_category(self):
        if (self.cleaned_data.get('product') and
                 self.cleaned_data.get('product') in ('GLUU', 'OXD', 'SUP_GLUU') ):
            if not self.cleaned_data.get('ticket_category'):
                raise forms.ValidationError(_('Please specify the issue category'))
        return self.cleaned_data.get('ticket_category')

    def clean_os_version_name(self):

        if not self.cleaned_data.get('os_version_name') or self.cleaned_data.get('os_version_name') < 0:

            raise forms.ValidationError(_('Please enter os version in positive numbers.'))

        return self.cleaned_data.get('os_version_name')
Exemplo n.º 20
0
class NamedUserTicketForm(UserTicketForm):

    is_private = forms.ChoiceField(
        choices=constants.TICKET_PRIVACY,
        initial=True,
        label=_('Privacy'),
        required=False
    )

    issue_type = forms.ChoiceField(
        choices=constants.ISSUE_TYPE_CREATE,
        label=_('Issue Type'),
    )

    attachment = forms.FileField(widget=forms.FileInput(attrs={'multiple':"true"}), required=False)
    #forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    #forms.FileField(max_length=255,required=False)
    # forms.FileField(widget=forms.FileInput(attrs={'multiple':"true"}))



    file_upload_layout = FieldWithButtons(Div('attachment',StrictButton(
        'Add new file',
        css_id='add_new_file',
        css_class='btn btn-xs btn-success'),
        css_class='full-wide layout_sec'),
    )

    fine_uploader_layout= Layout(

        Div(
            css_id= 'fine-uploader-manual-trigger',
            css_class='layout_sec',
        ),
    )


    uploaded_files_layout = Layout()


    class Meta(UserTicketForm.Meta):

        fields = UserTicketForm.Meta.fields + ('issue_type', 'is_private')

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

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

        self.uploaded_files_layout = Layout()

        if self.instance and self.instance.issue_type:
            self.fields['issue_type'].choices = constants.ISSUE_TYPE
        else:
            self.fields['issue_type'].choices = constants.ISSUE_TYPE_CREATE

        if self.instance.id and self.instance.owned_by.is_basic:
            self.fields['issue_type'].required = False

        if self.instance and self.instance.ticket_documents.all():

            for i, d in enumerate(self.instance.ticket_documents.all()):

                self.uploaded_files_layout.append(
                    HTML(
                        '''
                        <div class="form-horizontal">
                        <div class="form-group">
                          <label class="control-label col-lg-3" for="id_file">File</label>
                          <div class="controls col-lg-8">
                            <span>{}</span>
                            <a type="button" style="margin-bottom:5px;margin-left:5px" id="{}" class="btn btn-xs btn-danger pull-right delete_file">
                              Delete file
                            </a>
                            <a class="btn btn-default btn-xs pull-right" target="_blank" href="{}" style="margin-right:15px;">
                              <span class="glyphicon glyphicon-file"></span>Download
                            </a>
                          </div>
                        </div></div>'''.format(d.filename, d.id, d.file.url)
                    )
                )

        self.helper.layout = Layout(
            self.classification_layout,
            self.uploaded_products_layout,
            self.product_layout,
            self.category_layout,
            self.description_layout,
            self.additional_layout,
            self.fine_uploader_layout,
            # self.file_upload_layout,
            # self.uploaded_files_layout,
            self.button_layout
        )

    def clean_issue_type(self):
        if (self.cleaned_data.get('product') and
                 self.cleaned_data.get('product') in ('GLUU', 'OXD', 'SUP_GLUU') ):
            if not self.cleaned_data.get('issue_type'):
                raise forms.ValidationError(_('Please specify the issue type'))
        return self.cleaned_data.get('issue_type')
Exemplo n.º 21
0
 def test__getattr__append_layout_object(self):
     layout = Layout(Div('email'))
     layout.append('password1')
     self.assertTrue(isinstance(layout[0], Div))
     self.assertTrue(isinstance(layout[0][0], string_types))
     self.assertTrue(isinstance(layout[1], string_types))
Exemplo n.º 22
0
def test__getattr__append_layout_object():
    layout = Layout(Div("email"))
    layout.append("password1")
    assert isinstance(layout[0], Div)
    assert isinstance(layout[0][0], str)
    assert isinstance(layout[1], str)