Exemplo n.º 1
0
def get_response_dict(context, helper, layout, is_formset, template_pack, is_subform):
    """
    Returns a dictionary with all the parameters necessary to render the form/formset in a template.

    :param context: `django.template.Context` for the node
    :param attrs: Dictionary with the helper's attributes used for rendering the form/formset
    :param is_formset: Boolean value. If set to True, indicates we are working with a formset.

    """
    if layout is None:
        layout = Layout()
    attrs = layout.get_attributes(helper=helper, template_pack=template_pack)
    form_type = 'form'
    if is_formset:
        form_type = 'formset'

    # We take form/formset parameters from attrs if they are set, otherwise we use defaults
    response_dict = {
        'template_pack': settings.CRISPY_TEMPLATE_PACK,
        '%s_action' % form_type: attrs['attrs'].get("action", ''),
        '%s_method' % form_type: attrs.get("form_method", 'post'),
        '%s_tag' % form_type: attrs.get("form_tag", True),
        '%s_class' % form_type: attrs['attrs'].get("class", ''),
        '%s_id' % form_type: attrs['attrs'].get("id", ""),
        '%s_style' % form_type: attrs.get("form_style", None),
        'form_error_title': attrs.get("form_error_title", None),
        'formset_error_title': attrs.get("formset_error_title", None),
        'form_show_errors': attrs.get("form_show_errors", True),
        'help_text_inline': attrs.get("help_text_inline", False),
        'html5_required': attrs.get("html5_required", False),
        'form_show_labels': attrs.get("form_show_labels", True),
        'disable_csrf': attrs.get("disable_csrf", False),
        'inputs': attrs.get('inputs', []),
        'is_formset': is_formset,
        '%s_attrs' % form_type: attrs.get('attrs', ''),
        'flat_attrs': attrs.get('flat_attrs', ''),
        'error_text_inline': attrs.get('error_text_inline', True),
        'field_class': attrs.get('field_class', ''),
        'label_class': attrs.get('label_class', ''),
        'label_offset': attrs.get('label_offset', ''),
    }

    if context.get('is_subform') or is_subform:
        response_dict['%s_tag' % form_type] = False
        response_dict['disable_csrf'] = True
    else:
        response_dict['is_subform'] = True

    # Handles custom attributes added to helpers
    for attribute_name, value in attrs.items():
        if attribute_name not in response_dict:
            response_dict[attribute_name] = value

    if 'csrf_token' in context:
        response_dict['csrf_token'] = context['csrf_token']

    if 'helper' in context:
        response_dict['helper'] = context['helper']

    return response_dict
Exemplo n.º 2
0
class TowerHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(TowerHelper, self).__init__(*args, **kwargs)
        self.form_tag = False
        self.add_input(
            Submit("add-tower", "Add Tower", css_class='btn-block',
                   css_id='add-tower'))
        self.add_input(
            Submit('project-details', 'Submit', css_class='btn-block',
                   css_id='submit-project-details')
        )
        self.disable_csrf = True
        self.layout = Layout(
            Fieldset(
                'Tower Info',
                Div(
                    'name',
                    css_class='col-md-6',
                    style='padding-left:0px'),
                Div(
                    'floors_completed',
                    css_class='col-md-6',
                    style='padding-right:0px'),
                Div('finishing_status',
                    'other_status',
                    css_class='col-md-12',
                    style='padding:0px'),
                Div(
                    'image',
                    css_class='col-md-12',
                    style='padding:0% 0% 5% 0%'
                ))
        )
        self.layout.extend(['DELETE'])
Exemplo n.º 3
0
class DeveloperProjectHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(DeveloperProjectHelper, self).__init__(*args, **kwargs)
        self.form_tag = False
        self.add_input(
            Submit("add-project", "Add Project", css_class='btn-block',
                   css_id='add-project'))
        self.add_input(Submit("builder-details", "Save", css_class='btn-block',
                              css_id='submit-builder-details'))
        self.disable_csrf = True
        self.layout = Layout(
            'project_name',
            Div(
                Field('launch_date', css_class='month-year'),
                css_class='col-md-6',
                style='padding-left:0px'
            ),
            Div(
                Field('possession_date', css_class='month-year'),
                css_class='col-md-6',
                style='padding-right:0px'
            ),
            'developer',

        )
        self.layout.extend(['DELETE'])
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))
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 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.º 8
0
class UpdateSuggestionHelper(FormHelper):

    def __init__(self, suggestion = None, url = None, description=None, *args, **kwargs):
        try:
            super(UpdateSuggestionHelper, self).__init__(*args, **kwargs)
            #  TODO: Assert that the model to be changed is the same as the instance
            submit_url = None
            name = None

            instance = suggestion.primary.instance

            if url:
                submit_url = kwargs.get('url')
            if instance:
                meta = instance._meta
                app, mod, name = meta.app_label, meta.model_name, meta.verbose_name

                if instance.pk and not submit_url:
                    submit_url = '/rest/{}/{}/{}/'.format(app, mod, instance.pk)

            if suggestion and not submit_url:

                if suggestion.state != 'A':

                    model = suggestion.primary.retrieve_model
                    i = model()
                    app, mod, name = i._meta.app_label, i._meta.model_name, i._meta.verbose_name
                    submit_url = '{}_{}_/'.format(suggestion.url, suggestion.pk)

                else:
                    submit_url = suggestion.url

            else:
                if not submit_url:
                    submit_url = suggestion.url+ 'ERROR - might not be a primary instance?'

            self.attrs = {'action': '/suggest/suggest/'}
            self.form_method = 'POST'
            self.layout = Layout(
                Hidden('_method', 'PATCH'),
                Hidden('_url', submit_url),
                Hidden('_action', 'UM'),
                Hidden('_description', kwargs.get('description') or 'Modify a {} in the database'.format(name)),
                Hidden('_affected_instance_primary', 'suggest_suggest {}'.format(suggestion.pk)),
                Hidden('_next', '/suggest/#object=_suggestion_'),
                manyfieldlayout(instance),
                Layout(*[Hidden('__nochange', f) for f in kwargs.get('nochange', [])]),
                # HTML('''<div class="alert alert-{}" role="alert">{}</div>'''.format('info', 'UpdateSuggestionHelper loaded successfully'))
            )

        except Exception, e:
            super(UpdateSuggestionHelper, self).__init__(*args, **kwargs)
            self.layout = Layout()
            self.layout.extend([HTML('''<div class="alert alert-{}" role="alert">{}</div>'''.format('warning', e.message))])
            self.layout.extend([HTML('''<div class="alert alert-{}" role="alert">{}</div>'''.format('warning', 'UpdateSuggestionHelper'))])
            raise
Exemplo n.º 9
0
class MessageFormHelper(FormHelper):
    '''
    Returns a FormHelper with a bootstrap message
    :return:
    '''
    def __init__(self, message, cssclass="warning", *args, **kwargs):
        #  Possible cssclass values for bootstrap are success, info, warning, and danger
        super(MessageFormHelper, self).__init__(*args, **kwargs)
        self.layout = Layout()
        self.layout.extend([HTML('''<div class="alert alert-{}" role="alert">{}</div>'''.format(cssclass, message))])
Exemplo n.º 10
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.º 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
class UpdateFormHelper(FormHelper):

    def __init__(self, instance=None, suggestion=None, url=None, description=None, *args, **kwargs):

        try:

            super(UpdateFormHelper, self).__init__()

            if hasattr(instance, '_meta') and hasattr(instance, 'pk'):
                app = instance._meta.app_label
                mod = instance._meta.model_name
                pk = getattr(instance, 'pk')
                name = instance._meta.verbose_name
                aip = Hidden('_affected_instance_primary', '{}_{} {}'.format(app, mod, pk))

            elif hasattr(suggestion, 'primary') and hasattr(suggestion, 'pk'):
                app, mod = suggestion.primary.model_name.split('_')
                name = "suggestion"
                pk = '_%s_'%(getattr(suggestion, 'pk'))
                instance = "suggestion"
                aip = Hidden('_affected_instance_primary', '{}_{} {}'.format('suggest', 'suggest', getattr(suggestion, 'pk')))

            else:
                raise AssertionError('Supply either a Suggestion or a model instance')

            if not description:
                description = kwargs.get('description', 'Modify a {} ({}) in the database'.format(name, instance))

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

            self.attrs = {'action': '/suggest/suggest/'}
            self.form_method = 'POST'
            self.form_tag = True
            self.layout = Layout(
                Hidden('_method', 'PATCH'),
                Hidden('_url', submit_url),
                Hidden('_action', 'UM'),
                Hidden('_description', description),
                Hidden('__formtype', "Update Form"),
                manyfieldlayout(instance),
                aip)

        except Exception, e:
            super(UpdateFormHelper, self).__init__()
            self.layout = Layout()
            self.layout.extend([HTML('''<div class="alert alert-{}" role="alert">{}</div>'''.format('warning', e.message))])
            raise
Exemplo n.º 13
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.º 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'),
            )
        )
def test_layout_get_field_names():
    layout_1 = Layout(
        Div('field_name'),
        'password'
    )
    assert layout_1.get_field_names() == [
        [[0, 0], 'field_name'],
        [[1], 'password'],
    ]

    layout_2 = Layout(
        Div('field_name'),
        'password',
        Fieldset('legend', 'extra_field')
    )
    assert layout_2.get_field_names() == [
        [[0, 0], 'field_name'],
        [[1], 'password'],
        [[2, 0], 'extra_field'],
    ]

    layout_3 = Layout(
        Div(
            Div(
                Div('email')
            ),
            Div('password1'),
            'password2'
        )
    )
    assert layout_3.get_field_names() == [
        [[0, 0, 0, 0], 'email'],
        [[0, 1, 0], 'password1'],
        [[0, 2], 'password2'],
    ]
Exemplo n.º 16
0
    def test_layout_get_field_names(self):
        layout_1 = Layout(Div("field_name"), "password")
        self.assertEqual(layout_1.get_field_names(), [[[0, 0], "field_name"], [[1], "password"]])

        layout_2 = Layout(Div("field_name"), "password", Fieldset("legend", "extra_field"))
        self.assertEqual(
            layout_2.get_field_names(), [[[0, 0], "field_name"], [[1], "password"], [[2, 0], "extra_field"]]
        )

        layout_3 = Layout(Div(Div(Div("email")), Div("password1"), "password2"))
        self.assertEqual(
            layout_3.get_field_names(), [[[0, 0, 0, 0], "email"], [[0, 1, 0], "password1"], [[0, 2], "password2"]]
        )
Exemplo n.º 17
0
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')  #take current user
        super(WoCompletion_form, self).__init__(*args, **kwargs)

        #get actions
        actDict = {}
        for action in self.user.actions.all():
            actDict[action.pk] = action.name

        # Converting into list of tuple
        actlist = list(actDict.items())
        self.fields['status'].widget = Select(choices=actlist)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Row(Column('status', css_class='form-group col-md-4 mb-0'),
                Column('manPower', css_class='form-group col-md-4 mb-0'),
                Column('duration', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'),
            Row(Column('activity', css_class='form-group col-md-4 mb-0'),
                Column('material', css_class='form-group col-md-4 mb-0'),
                Column('tool', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'), Submit('submit', 'Submit'))
Exemplo n.º 18
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['amount'].widget.attrs['class'] = 'form-control-sm'
     self.fields['amount'].widget.attrs['style'] = 'text-align: right;'
     self.fields['date'].widget.attrs['class'] = 'form-control-sm'
     self.fields['date'].widget.attrs['style'] = 'text-align: center;'
     self.fields['date'].widget.attrs['value'] = timezone.now().strftime(
         '%Y-%m-%d')
     self.helper = FormHelper()
     self.helper.form_method = 'post'
     self.helper.form_tag = False
     self.helper.disable_csrf = False
     self.helper.form_class = 'form-horizontal'
     self.helper.label_class = 'col-4 h5'
     self.helper.field_class = 'col-8'
     self.helper.layout = Layout(
         FieldWithButtons('date',
                          StrictButton(
                              '<i class="far fa-calendar-alt"></i>',
                              css_class='btn-sm btn-date'),
                          css_class='form-control-sm'),
         Div('amount', css_class='form-control-sm'),
     )
Exemplo n.º 19
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Hidden('user_created', '{{ user.id }}'),
         Hidden('user_updated', '{{ user.id }}'),
         'name',
         'medical_specialty',
         'obs',
         HTML('''               
              <div class="row">    
                 <div class="col-sm-6">
                     <span class="float-left">
                         <button type="submit" class="btn btn-primary">Salvar</button>  	                              
                     </span>
                 </div>
                 <div class="col-sm-6">
                     <span class="float-right">
                         <a href="{% url 'url_typeitems_list' %}" class="btn btn-warning">Voltar</a>
                     </span>  
                 </div>
             </div>'''),
     )
Exemplo n.º 20
0
Arquivo: forms.py Projeto: Uglaos/opg
class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user', )
        labels = {
            'name': 'Ime',
            'surname': 'Prezime',
            'opg_name': 'Naziv OPG-a',
            'address': 'Adresa',
            'phone': 'Telefon',
        }

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'autofocus': 'autofocus'})

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.label_class = 'col-lg-3'
    helper.field_class = 'col-lg-7'
    helper.layout = Layout(
        Field('name', 'surname', 'opg_name', 'address', 'phone'), )
    helper.form_method = 'POST'
Exemplo n.º 21
0
 def __init__(self, *args, **kwargs):
     # kwargs.pop('instance')
     super(UpdateProfileForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_id = 'id_profile_edit_form'
     self.helper.form_method = 'post'
     self.helper.form_class = 'form-horizontal'
     self.helper.label_class = 'col-lg-3'
     self.helper.field_class = 'col-lg-4'
     self.helper.layout = Layout(
         Fieldset(
             '',
             Field('sex', css_class='selectpicker'),
             'city',
             Field('timezone', css_class='selectpicker'),
             Field('avatar', template='avatar_template.html'),
         ),
         ButtonHolder(
             Submit('update', u'Update', css_class='button create'),
             Button('cancel',
                    'Cancel',
                    css_class='btn-default',
                    onclick="window.history.back()")))
Exemplo n.º 22
0
    def __init__(self, user, *args, **kwargs):
        self.user = user
        if hasattr(self.user, 'profile'):
            profile = self.user.profile
        else:
            profile = None

        super().__init__(*args, **kwargs, instance=profile)

        self.fields['address'].widget.attrs['rows'] = 5
        self.fields['date_of_birth'].widget = DatePickerInput(startOffset=100,
                                                              endOffset=10)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            AvatarPreview('profile_picture'), RowCol('first_name',
                                                     'last_name'),
            RowCol('date_of_birth', 'email'),
            RowCol('address', RowCol('pincode',
                                     'post_office',
                                     col_css='col-12')),
            RowCol('district', 'state'), RowCol('role', 'jersey_size'),
            Submit('Submit', 'submit'))
Exemplo n.º 23
0
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)

        helpers.custom_fields(self)

        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-4'
        self.helper.layout = Layout('username', 'email', 'password',
                                    'password_again', 'first_name',
                                    'last_name', 'job_title', 'organisation',
                                    'phone_number')

        custom_fields = CustomField.objects.all().order_by('order')
        for custom_field in custom_fields:
            self.helper.layout.append(custom_field.id)

        self.helper.layout.append(
            Div(
                Submit('submit', _(u'Register'), css_class='btn btn-default'),
                css_class='col-lg-offset-2 col-lg-4',
            ), )
Exemplo n.º 24
0
    def __init__(self, *args, **kwargs):
        super(MemberForm, self).__init__(*args, **kwargs)

        self.helper.form_tag = False
        self.helper.layout = Layout(
            'first_name',
            'surname',
            'nick',
            'official_first_names',
            'muncipality',
            'birth_date',
            'phone',
            'email',
        )

        self.fields[
            'muncipality'].help_text = 'Yhdistyslaki vaatii yhdistystä pitämään jäsenistään luetteloa, josta ilmenevät jäsenen täydellinen nimi ja kotikunta.'
        self.fields['phone'].help_text = None
        self.fields['email'].help_text = self.fields[
            'email'].help_text.replace('tapahtumaan', 'yhdistykseen')

        for field_name, field in self.fields.items():
            field.required = field_name in ['first_name', 'surname']
Exemplo n.º 25
0
 def __init__(self, *args, **kwargs):
     self.helper = FormHelper()
     self.helper.form_tag = False
     self.helper.disable_csrf = True
     self.helper.layout = Layout(
         Fieldset(
             'Filter Pack',
             Div(
                 Div(AppendedText('filter_pack_from', 'ft'),
                     css_class='col-md-2'),
                 Div(AppendedText('filter_pack_to', 'ft'),
                     css_class='col-md-2'),
                 Div(AppendedText('filter_pack_thickness', 'in'),
                     css_class='col-md-2'),
                 css_class='row',
             ),
             Div(
                 Div('filter_pack_material', css_class='col-md-3'),
                 Div('filter_pack_material_size', css_class='col-md-3'),
                 css_class='row',
             ),
         ))
     super(ActivitySubmissionFilterPackForm, self).__init__(*args, **kwargs)
Exemplo n.º 26
0
 def __init__(self, *args, **kwargs):
     self.helper = FormHelper()
     self.helper.form_tag = False
     self.helper.disable_csrf = True
     self.helper.layout = Layout(
         Fieldset(
             'Well Development',
             Div(
                 Div('development_method', css_class='col-md-3'),
                 css_class='row',
             ),
             Div(
                 Div(AppendedText('development_hours', 'hrs'),
                     css_class='col-md-3'),
                 css_class='row',
             ),
             Div(
                 Div('development_notes', css_class='col-md-6'),
                 css_class='row',
             ),
         ))
     super(ActivitySubmissionDevelopmentForm,
           self).__init__(*args, **kwargs)
Exemplo n.º 27
0
 def __init__(self, *args, **kwargs):
     super(RegistrationForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper(self)
     self.helper.form_show_labels = False
     self.helper.layout = Layout(
         Field('first_name',
               placeholder='First name',
               css_class='input-xlarge'),
         Field('last_name',
               placeholder='Last name',
               css_class='input-xlarge'),
         Field('email', placeholder='Email', css_class='input-xlarge'),
         Field('password', css_class='input-xlarge',
               placeholder='Password'),
         FormActions(
             Submit('submit',
                    value='Sign Up',
                    css_class='btn-info btn-large btn-embossed mlm',
                    css_id='registrationButton'),
             HTML(
                 '<i id="spinnerSignup" class="icon-spinner icon-spin icon-large" '
                 'style="font-size: 18px; padding: 3px; display:none;"></i>'
             )))
Exemplo n.º 28
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Row(
             Column("name"),
             Column(AppendedText("url", clipboard_html("#id_url"))),
             css_class="form-row",
         ),
         Row(
             Column(AppendedText("username",
                                 clipboard_html("#id_username"))),
             Column(
                 PrependedAppendedText(
                     "password",
                     showpassword_html("#id_password"),
                     clipboard_html("#id_password"),
                 )),
             css_class="form-row",
         ),
         "details",
         FormActions(Submit("save", "Update secret"), ),
     )
Exemplo n.º 29
0
 def __init__(self, *args, **kwargs): #constructor
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_id = 'id_pwd_lang'
     self.helper.form_class = 'form-horizontal'
     self.helper.form_show_labels = False
     self.helper.add_input(Submit('Submit', 'Save', css_class='btn-applicant'))
     self.helper.add_input(Button('/handicapped/pwd-lang', 'Cancel', css_class='btn-primary btn-danger-dark', css_id="cancel-language-form"))
     self.helper.layout = Layout(
         Fieldset(
             '',
             Div(
                 Div(HTML(''' <h5 class="text-white">Add Language</h5> '''), css_class="col-12 pl-0"),
                 Div(
                     'language', css_class="col-3 mr-2",
                 ),
                 Div(
                     'proficiency', css_class="col-3",
                 ),
                 css_class='row',
             ),
         ),
     )
Exemplo n.º 30
0
 def get_form(self):
     form = super().get_form()
     form.helper = FormHelper()
     form.helper.layout = Layout(
         'role',
         'location',
         Row(
             Column('date', css_class='col-sm-4'),
             Column('start_time', css_class='col-sm-4'),
             Column('end_time', css_class='col-sm-4'),
             css_class='form-row',
         ),
         Field('needs_dbs'),
         Field('volunteer_can_accept'),
         Field('volunteer'),
         Field('notes'),
         FormActions(
             Submit('save', 'Save'),
             Button('delete', 'Delete'),
             Button('cancel', 'Cancel'),
         )
     )
     return form
Exemplo n.º 31
0
def test_field_type_hidden():
    template = Template("""
        {% load crispy_forms_tags %}
        {% crispy test_form %}
    """)

    test_form = SampleForm()
    test_form.helper = FormHelper()
    test_form.helper.layout = Layout(
        Field('email', type="hidden", data_test=12),
        Field('datetime_field'),
    )

    c = Context({
        'test_form': test_form,
    })
    html = template.render(c)

    # Check form parameters
    assert html.count('data-test="12"') == 1
    assert html.count('name="email"') == 1
    assert html.count('class="dateinput') == 1
    assert html.count('class="timeinput') == 1
Exemplo n.º 32
0
class PaymentDetailsForm(ModelForm):
    class Meta:
        model = PaymentDetail
        fields = ('name', 'email', 'mobile', 'amount', 'Description')
        labels = {
            'name': "Name",
            'email': "Email Id",
            'mobile': "Contact Number",
            'amount': "Amount",
            'Description': "Description"
        }

    helper = FormHelper()
    helper.form_class = 'form_group'
    helper.form_method = 'post'
    helper.layout = Layout(
        Field('name', css_class='form-control'),
        Field('email', css_class='form-control'),
        Field('mobile', css_class='form-control'),
        Field('amount', css_class='form-control'),
        Field('Description', css_class='form-control'),
        Submit('Submit', 'Submit', css_class="btn btn-primary"),
    )
Exemplo n.º 33
0
 def __init__(self, *args, **kwargs):
     super(RegisterForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_id = 'id_register_form'
     self.helper.form_method = 'post'
     self.helper.form_class = 'form-horizontal'
     self.helper.label_class = 'col-lg-5 col-md-5 col-sm-5 col-xs-5'
     self.helper.field_class = 'col-lg-6 col-md-6 col-sm-6 col-xs-6'
     self.helper.layout = Layout(
         Fieldset(
             '',
             'first_name',
             'last_name',
             'username',
             'password',
             'email',
             'sex',
             'city',
             Field('timezone', css_class='selectpicker'),
             'avatar',
         ),
         ButtonHolder(Submit('create', u'Create',
                             css_class='button create')))
Exemplo n.º 34
0
    def test_get_layout_objects(self):
        layout_1 = Layout(
            Div()
        )
        self.assertEqual(layout_1.get_layout_objects(Div), [
            [[0], 'div']
        ])

        layout_2 = Layout(
            Div(
                Div(
                    Div('email')
                ),
                Div('password1'),
                'password2'
            )
        )
        self.assertEqual(layout_2.get_layout_objects(Div), [
            [[0], 'div']
        ])
        self.assertEqual(layout_2.get_layout_objects(Div, max_level=1), [
            [[0], 'div'],
            [[0, 0], 'div'],
            [[0, 1], 'div']
        ])
        self.assertEqual(layout_2.get_layout_objects(Div, max_level=2), [
            [[0], 'div'],
            [[0, 0], 'div'],
            [[0, 0, 0], 'div'],
            [[0, 1], 'div']
        ])

        layout_3 = Layout(
            'email',
            Div('password1'),
            'password2',
        )
        self.assertEqual(layout_3.get_layout_objects(basestring, max_level=2), [
            [[0], 'email'],
            [[1, 0], 'password1'],
            [[2], 'password2']
        ])

        layout_4 = Layout(
            Div(
                Div('field_name'),
                'field_name2',
            ),
            Div('password'),
            'extra_field'
        )
        self.assertEqual(layout_4.get_layout_objects(Div), [
            [[0], 'div'],
            [[1], 'div']
        ])
        self.assertEqual(layout_4.get_layout_objects(Div, max_level=1), [
            [[0], 'div'],
            [[0, 0], 'div'],
            [[1], 'div']
        ])
Exemplo n.º 35
0
    def test_get_layout_objects(self):
        layout_1 = Layout(Div())
        self.assertEqual(layout_1.get_layout_objects(Div), [[[0], "div"]])

        layout_2 = Layout(Div(Div(Div("email")), Div("password1"), "password2"))
        self.assertEqual(layout_2.get_layout_objects(Div), [[[0], "div"]])
        self.assertEqual(
            layout_2.get_layout_objects(Div, max_level=1), [[[0], "div"], [[0, 0], "div"], [[0, 1], "div"]]
        )
        self.assertEqual(
            layout_2.get_layout_objects(Div, max_level=2),
            [[[0], "div"], [[0, 0], "div"], [[0, 0, 0], "div"], [[0, 1], "div"]],
        )

        layout_3 = Layout("email", Div("password1"), "password2")
        self.assertEqual(
            layout_3.get_layout_objects(basestring, max_level=2),
            [[[0], "email"], [[1, 0], "password1"], [[2], "password2"]],
        )

        layout_4 = Layout(Div(Div("field_name"), "field_name2"), Div("password"), "extra_field")
        self.assertEqual(layout_4.get_layout_objects(Div), [[[0], "div"], [[1], "div"]])
        self.assertEqual(layout_4.get_layout_objects(Div, max_level=1), [[[0], "div"], [[0, 0], "div"], [[1], "div"]])
def test_get_layout_objects():
    layout_1 = Layout(
        Div()
    )
    assert layout_1.get_layout_objects(Div) == [[[0], 'div']]

    layout_2 = Layout(
        Div(
            Div(
                Div('email')
            ),
            Div('password1'),
            'password2'
        )
    )
    assert layout_2.get_layout_objects(Div) == [[[0], 'div']]
    assert layout_2.get_layout_objects(Div, max_level=1) == [
        [[0], 'div'],
        [[0, 0], 'div'],
        [[0, 1], 'div']
    ]
    assert layout_2.get_layout_objects(Div, max_level=2) == [
        [[0], 'div'],
        [[0, 0], 'div'],
        [[0, 0, 0], 'div'],
        [[0, 1], 'div']
    ]

    layout_3 = Layout(
        'email',
        Div('password1'),
        'password2',
    )
    assert layout_3.get_layout_objects(string_types, max_level=2) == [
        [[0], 'email'],
        [[1, 0], 'password1'],
        [[2], 'password2']
    ]

    layout_4 = Layout(
        Div(
            Div('field_name'),
            'field_name2',
        ),
        Div('password'),
        'extra_field'
    )
    assert layout_4.get_layout_objects(Div) == [
        [[0], 'div'],
        [[1], 'div']
    ]
    assert layout_4.get_layout_objects(Div, max_level=1) == [
        [[0], 'div'],
        [[0, 0], 'div'],
        [[1], 'div']
    ]