コード例 #1
0
ファイル: forms.py プロジェクト: adityacharlie/code_samples
 def __init__(self, *args, **kwargs):
     super(RegistrationForm, self).__init__(*args, **kwargs)
     self.common_layout = Layout(
         MultiField(
             "<h5>Registration is free. Start by giving us your e-mail \
             address, and we'll send you instructions on how to continue.\
             We will not spam you or give your e-mail address to anybody.\
             </h5>"),
         MultiField("<h4>Personal Info</h4>"),
         'username',
         'password1',
         'password2',
         'company_name',
         MultiField("<h4>Contact Info</h4>"),
         'email',
         'website',
         'phone_number',
         'address',
         'city',
         'region',
         'country',
         'postal_code',
         FormActions(
             Submit('save', 'Validate & Submit'),
             Button('cancel', 'Cancel', onclick="window.history.back()")),
     )
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Div(Div(self.common_layout, css_class='col-md-6'),
             css_class="row"))
コード例 #2
0
 def __init__(self, *args, **kwargs):
     super(UserProfileForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.form_class = 'dropzone'
     self.helper.form_action = '#'
     self.helper.layout = Layout(
         MultiField(
             HTML(
                 "<img src='{{ user.userprofile.avatar_url.url_60x60 }}'>"),
             Fieldset(
                 'Sobre ti',
                 'avatar_url',
                 'about',
                 'facebook',
                 'twitter',
                 css_class='large-6 medium-6 columns',
             ),
             Fieldset(
                 'Habilidades',
                 'category',
                 HTML(
                     "<a  href='/crea/habilidad/' target='_blank'><i class='fa fa-life-ring'></i> Falta alguna habilidad en el listado?</a>"
                 ),
                 css_class='large-6 medium-6 columns'),
             ButtonHolder(
                 Submit('submit',
                        'Guardar cambios',
                        css_class='button radius'))))
コード例 #3
0
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id = 'orderform'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'

        self.helper.layout = Layout(
            MultiField(
                'first arg is the legend of the fieldset',
                Div('F_Date',
                    style="background: white;",
                    title="Explication title",
                    css_class="bigdivs"),
                'F_SKID',
                'F_TSType',
                'F_CurID',
                'F_Qty',
                'F_Rate',
                'F_Nav',
                'F_Fee',
                'F_Exp',
                'F_Payable',
                'F_Receivable',
            ),
            AppendedText('F_Amt', '$', active=True),
            Field('F_Note',
                  id="password-field",
                  css_class="passwordfields",
                  title="Explanation"),
            #Field('slider', template="custom-slider.html"),
            ButtonHolder(Submit('submit', 'Submit', css_class='button white')),
            FormActions(Submit('save', 'Save changes'),
                        Button('cancel', 'Cancel')))
        super(orderform, self).__init__(*args, **kwargs)
コード例 #4
0
ファイル: forms.py プロジェクト: pramodpalIndia/onhand
 def __init__(self, *args, **kwargs):
     super(CommonLayout, self).__init__(
         MultiField(
             'username',
             'lastname',
         )
     )
コード例 #5
0
ファイル: forms.py プロジェクト: budiryan/glucose-tracker
    def __init__(self, *args, **kwargs):
        super(GlucoseImportForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'

        self.helper.layout = Layout(
            MultiField(
                None,
                HTML('''
                    {% if messages %}
                    {% for message in messages %}
                    <p {% if message.tags %}
                    class="alert alert-{{ message.tags }}"
                    {% endif %}>{{ message }}</p>{% endfor %}{% endif %}
                    '''),
                Div(
                    'file',
                    FormActions(
                        Submit('submit', 'Import'),
                        css_class='pull-right',
                    ),
                    css_class='well col-xs-10 col-sm-8 col-md-8',
                ),
            ), )
コード例 #6
0
ファイル: test_layout.py プロジェクト: qaz3320/Jeap
    def test_second_layout_multifield_column_buttonholder_submit_div(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                MultiField("Some company data",
                           'is_company',
                           'email',
                           css_id="multifield_info",
                           title="multifield_title",
                           multifield_test="123"),
                Column(
                    'first_name',
                    'last_name',
                    css_id="column_name",
                    css_class="columns",
                ),
                ButtonHolder(
                    Submit('Save the world',
                           '{{ value_var }}',
                           css_class='button white',
                           data_id='test',
                           data_name='test'), Submit('store',
                                                     'Store results')),
                Div('password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                    test_markup="123")))

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({
            'form': TestForm(),
            'form_helper': form_helper,
            'value_var': "Save"
        })
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('title="multifield_title"' in html)
        self.assertTrue('multifield-test="123"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('button white' in html)
        self.assertTrue('data-id="test"' in html)
        self.assertTrue('data-name="test"' in html)
        self.assertTrue('name="save-the-world"' in html)
        self.assertTrue('value="Save"' in html)
        self.assertTrue('name="store"' in html)
        self.assertTrue('value="Store results"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
        self.assertTrue('test-markup="123"' in html)
コード例 #7
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Column(
             HTML(
                 """
                 <h2>Edit profile</h2>
                 """, ),
             Field('about_me'),
             MultiField('badge_id',
                        template='users/widgets/multipleCheckboxes.html'),
             MultiField('color_value',
                        template='users/widgets/colorPicker.html',
                        css_class='p-0 m-0'),
             Submit('submit', 'Update', css_class="mb-4"),
             css_class='col-lg-8 mx-auto profileBoxes bg-white pt-2',
         ))
コード例 #8
0
def test_second_layout_multifield_column_buttonholder_submit_div():
    form_helper = FormHelper()
    form_helper.add_layout(
        Layout(
            MultiField(
                "Some company data",
                "is_company",
                "email",
                css_id="multifield_info",
                title="multifield_title",
                multifield_test="123",
            ),
            Column(
                "first_name",
                "last_name",
                css_id="column_name",
                css_class="columns",
            ),
            ButtonHolder(
                Submit(
                    "Save the world", "{{ value_var }}", css_class="button white", data_id="test", data_name="test"
                ),
                Submit("store", "Store results"),
            ),
            Div("password1", "password2", css_id="custom-div", css_class="customdivs", test_markup="123"),
        )
    )

    template = Template(
        """
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """
    )
    c = Context({"form": SampleForm(), "form_helper": form_helper, "value_var": "Save"})
    html = template.render(c)

    assert "multiField" in html
    assert "formColumn" in html
    assert 'id="multifield_info"' in html
    assert 'title="multifield_title"' in html
    assert 'multifield-test="123"' in html
    assert 'id="column_name"' in html
    assert 'class="formColumn columns"' in html
    assert 'class="buttonHolder">' in html
    assert 'input type="submit"' in html
    assert "button white" in html
    assert 'data-id="test"' in html
    assert 'data-name="test"' in html
    assert 'name="save-the-world"' in html
    assert 'value="Save"' in html
    assert 'name="store"' in html
    assert 'value="Store results"' in html
    assert 'id="custom-div"' in html
    assert 'class="customdivs"' in html
    assert 'test-markup="123"' in html
コード例 #9
0
def test_multifield_errors():
    form = SampleForm({
        'email': 'invalidemail',
        'password1': 'yes',
        'password2': 'yes',
    })
    form.helper = FormHelper()
    form.helper.layout = Layout(MultiField('legend', 'email'))
    form.is_valid()

    form.helper.form_show_errors = True
    html = render_crispy_form(form)
    assert html.count('error') == 3

    # Reset layout for avoiding side effects
    form.helper.layout = Layout(MultiField('legend', 'email'))
    form.helper.form_show_errors = False
    html = render_crispy_form(form)
    assert html.count('error') == 0
コード例 #10
0
def test_multifield_errors():
    form = SampleForm({
        "email": "invalidemail",
        "password1": "yes",
        "password2": "yes"
    })
    form.helper = FormHelper()
    form.helper.layout = Layout(MultiField("legend", "email"))
    form.is_valid()

    form.helper.form_show_errors = True
    html = render_crispy_form(form)
    assert html.count("error") == 3

    # Reset layout for avoiding side effects
    form.helper.layout = Layout(MultiField("legend", "email"))
    form.helper.form_show_errors = False
    html = render_crispy_form(form)
    assert html.count("error") == 0
コード例 #11
0
    def __init__(self, *args, **kwargs):
        super(WordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()

        self.helper.form_tag = False  # do not enclose into <form>, because there will be many
        self.helper.form_class = 'form-horizontal'
        self.helper.layout = Layout(
            Field('lemma'),
            MultiField(  # these fieldsets should eventually get rendered as tabs in an appearing div
                'Grammatical tags',  # legend
                Fieldset('pos', 'number')))
コード例 #12
0
def test_filter():
    helper = FormHelper()
    helper.layout = Layout(Div(
        MultiField("field_name"),
        "field_name2",
    ), Div("password"), "extra_field")
    assert helper.filter(Div, MultiField).slice == [[[0], "div"], [[1], "div"]]
    assert helper.filter(Div, MultiField,
                         max_level=1).slice == [[[0], "div"],
                                                [[0, 0], "multifield"],
                                                [[1], "div"]]
    assert helper.filter(MultiField, max_level=1).slice == [[[0, 0],
                                                             "multifield"]]
コード例 #13
0
def test_filter():
    helper = FormHelper()
    helper.layout = Layout(Div(
        MultiField('field_name'),
        'field_name2',
    ), Div('password'), 'extra_field')
    assert helper.filter(Div, MultiField).slice == [[[0], 'div'], [[1], 'div']]
    assert helper.filter(Div, MultiField,
                         max_level=1).slice == [[[0], 'div'],
                                                [[0, 0], 'multifield'],
                                                [[1], 'div']]
    assert helper.filter(MultiField, max_level=1).slice == [[[0, 0],
                                                             'multifield']]
コード例 #14
0
    def __init__(self, *args, **kwargs):
        super(GlucoseEmailReportForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-3 col-md-3'
        self.helper.field_class = 'col-sm-9 col-md-9'

        self. helper.layout = Layout(
            MultiField(
                None,
                Div(
                    HTML('''
                    {% if messages %}
                    {% for message in messages %}
                    <p {% if message.tags %}
                    class="alert alert-{{ message.tags }}"
                    {% endif %}>{{ message }}</p>{% endfor %}{% endif %}
                    '''),
                    Div(
                        'report_format',
                        Field('start_date', required=True),
                        Field('end_date', required=True),
                        'optional_fields',
                        css_class='well col-sm-4 col-md-4',
                    ),
                    Div('subject',
                        Field('recipient', placeholder='Email address',
                              required=True, autofocus=True),
                        'message',
                        FormActions(
                            Submit('submit', 'Send'),
                            css_class='pull-right'
                        ),
                        css_class='col-sm-8 col-md-8',
                    ),
                    css_class='row'
                ),
            ),
        )

        # Initial values.
        now = date.today()
        last_90_days = now - timedelta(days=90)
        self.fields['start_date'].initial = last_90_days.strftime(DATE_FORMAT)
        self.fields['end_date'].initial = now.strftime(DATE_FORMAT)

        self.fields['report_format'].initial = 'pdf'
        self.fields['optional_fields'].initial = ['notes']
        self.fields['subject'].initial = '[GlucoseTracker] Glucose Data Report'
コード例 #15
0
def test_layout_composition():
    form_helper = FormHelper()
    form_helper.add_layout(
        Layout(
            Layout(
                MultiField(
                    "Some company data",
                    "is_company",
                    "email",
                    css_id="multifield_info",
                ),
            ),
            Column(
                "first_name",
                # 'last_name', Missing a field on purpose
                css_id="column_name",
                css_class="columns",
            ),
            ButtonHolder(
                Submit("Save", "Save", css_class="button white"),
            ),
            Div(
                "password1",
                "password2",
                css_id="custom-div",
                css_class="customdivs",
            ),
        )
    )

    template = Template(
        """
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """
    )
    c = Context({"form": SampleForm(), "form_helper": form_helper})
    html = template.render(c)

    assert "multiField" in html
    assert "formColumn" in html
    assert 'id="multifield_info"' in html
    assert 'id="column_name"' in html
    assert 'class="formColumn columns"' in html
    assert 'class="buttonHolder">' in html
    assert 'input type="submit"' in html
    assert 'name="Save"' in html
    assert 'id="custom-div"' in html
    assert 'class="customdivs"' in html
    assert "last_name" not in html
コード例 #16
0
ファイル: test_layout.py プロジェクト: akki35/industryo
    def test_layout_composition(self):
        if settings.CRISPY_TEMPLATE_PACK != 'uni_form':
            warnings.warn(
                'skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' %
                settings.CRISPY_TEMPLATE_PACK)
            return
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Layout(
                    MultiField(
                        "Some company data",
                        'is_company',
                        'email',
                        css_id="multifield_info",
                    ), ),
                Column(
                    'first_name',
                    # 'last_name', Missing a field on purpose
                    css_id="column_name",
                    css_class="columns",
                ),
                ButtonHolder(Submit('Save', 'Save',
                                    css_class='button white'), ),
                Div(
                    'password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                )))

        template = loader.get_template_from_string(u"""
                {% load crispy_forms_tags %}
                {% crispy form form_helper %}
            """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('name="Save"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
        self.assertFalse('last_name' in html)
コード例 #17
0
    def test_multifield_errors(self):
        if settings.CRISPY_TEMPLATE_PACK != 'uni_form':
            warnings.warn(
                'skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' %
                settings.CRISPY_TEMPLATE_PACK)
            return
        form = TestForm({
            'email': 'invalidemail',
            'password1': 'yes',
            'password2': 'yes',
        })
        form.helper = FormHelper()
        form.helper.layout = Layout(MultiField('legend', 'email'))
        form.is_valid()

        form.helper.form_show_errors = True
        html = render_crispy_form(form)
        self.assertEqual(html.count('error'), 3)

        # Reset layout for avoiding side effects
        form.helper.layout = Layout(MultiField('legend', 'email'))
        form.helper.form_show_errors = False
        html = render_crispy_form(form)
        self.assertEqual(html.count('error'), 0)
コード例 #18
0
def test_layout_composition():
    form_helper = FormHelper()
    form_helper.add_layout(
        Layout(
            Layout(
                MultiField(
                    "Some company data",
                    'is_company',
                    'email',
                    css_id="multifield_info",
                ),
            ),
            Column(
                'first_name',
                # 'last_name', Missing a field on purpose
                css_id="column_name",
                css_class="columns",
            ),
            ButtonHolder(
                Submit('Save', 'Save', css_class='button white'),
            ),
            Div(
                'password1',
                'password2',
                css_id="custom-div",
                css_class="customdivs",
            )
        )
    )

    template = Template("""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
    c = Context({'form': SampleForm(), 'form_helper': form_helper})
    html = template.render(c)

    assert 'multiField' in html
    assert 'formColumn' in html
    assert 'id="multifield_info"' in html
    assert 'id="column_name"' in html
    assert 'class="formColumn columns"' in html
    assert 'class="buttonHolder">' in html
    assert 'input type="submit"' in html
    assert 'name="Save"' in html
    assert 'id="custom-div"' in html
    assert 'class="customdivs"' in html
    assert 'last_name' not in html
コード例 #19
0
ファイル: forms.py プロジェクト: shvechikov/glucose-tracker
    def __init__(self, *args, **kwargs):
        super(GlucoseImportForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'

        self.helper.layout = Layout(
            MultiField(
                None,
                Fieldset(
                    'Instructions',
                    HTML('''
                        To properly import your data, the CSV file must follow
                        this order and format: <br><br>
                        <ol>
                        <li>Value</li>
                        <li>Category (if no matching category in our system,
                        'No Category' will be assigned)</li>
                        <li>Date (in m/d/yyyy format, e.g. 5/6/2014 or
                        05/06/2014)</li>
                        <li> Time (in h:m am/pm format, e.g. 8:01 AM or
                        08:01 PM)</li>
                        <li>Notes</li>
                        </ol>
                        <p>You can also download this template as a guide:
                        <a href="{{ STATIC_URL }}samples/csv_import_template.csv">
                        csv_import_template.csv</a></p>
                        <br>
                        '''),
                ),
                HTML('''
                    {% if messages %}
                    {% for message in messages %}
                    <p {% if message.tags %}
                    class="alert alert-{{ message.tags }}"
                    {% endif %}>{{ message }}</p>{% endfor %}{% endif %}
                    '''),
                Div(
                    'file',
                    FormActions(
                        Submit('submit', 'Import'),
                        css_class='pull-right',
                    ),
                    css_class='well col-xs-10 col-sm-8 col-md-8',
                ),
            ), )
コード例 #20
0
 def test_filter(self):
     if settings.CRISPY_TEMPLATE_PACK != 'uni_form':
         warnings.warn(
             'skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' %
             settings.CRISPY_TEMPLATE_PACK)
         return
     helper = FormHelper()
     helper.layout = Layout(Div(
         MultiField('field_name'),
         'field_name2',
     ), Div('password'), 'extra_field')
     self.assertEqual(
         helper.filter(Div, MultiField).slice, [[[0], 'div'], [[1], 'div']])
     self.assertEqual(
         helper.filter(Div, MultiField, max_level=1).slice,
         [[[0], 'div'], [[0, 0], 'multifield'], [[1], 'div']])
     self.assertEqual(
         helper.filter(MultiField, max_level=1).slice,
         [[[0, 0], 'multifield']])
コード例 #21
0
ファイル: tests.py プロジェクト: vapask/django-crispy-forms
    def test_second_layout_multifield_column_buttonholder_submit_div(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                MultiField(
                    "Some company data",
                    'is_company',
                    'email',
                    css_id="multifield_info",
                ),
                Column(
                    'first_name',
                    'last_name',
                    css_id="column_name",
                    css_class="columns",
                ),
                ButtonHolder(Submit('Save', 'Save',
                                    css_class='button white'), ),
                Div(
                    'password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                )))

        template = get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('name="save"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
コード例 #22
0
    def test_form_show_errors(self):
        form = TestForm({
            'email': 'invalidemail',
            'first_name': 'first_name_too_long',
            'last_name': 'last_name_too_long',
            'password1': 'yes',
            'password2': 'yes',
        })
        form.helper = FormHelper()
        form.helper.layout = Layout(
            AppendedText('email', 'whatever'),
            PrependedText('first_name', 'blabla'),
            PrependedAppendedText('last_name', 'foo', 'bar'),
            MultiField('legend', 'password1', 'password2'))
        form.is_valid()

        form.helper.form_show_errors = True
        html = render_crispy_form(form)
        self.assertEqual(html.count('error'), 6)

        form.helper.form_show_errors = False
        html = render_crispy_form(form)
        self.assertEqual(html.count('error'), 0)
コード例 #23
0
ファイル: forms.py プロジェクト: zhoubear/libre
class ClientForm(forms.Form):
    server = forms.CharField(label=_('Server'))
    source = forms.ModelChoiceField(label=_('Source'), queryset=Source.objects.none(), to_field_name='slug')
    filters = forms.CharField(label=_('Filter'), widget=forms.Textarea, required=False)
    as_nested_list = forms.BooleanField(label=_('As nested list'), required=False)
    as_dict_list = forms.BooleanField(label=_('As dictionay list'), required=False)
    json_path = forms.CharField(label=_('JSON path'), required=False)
    groups = forms.CharField(label=_('Groups'), required=False)
    aggregates = forms.CharField(label=_('Aggregates'), required=False)
    renderer = forms.ChoiceField(label=_('Format'), choices=renderer_choices)
    query_string = forms.CharField(label=_('Query string'), widget=forms.Textarea, required=False)

    join_type = forms.ChoiceField(
        choices=JOIN_TYPE_CHOICES,
        widget=forms.RadioSelect,
        initial=JOIN_TYPE_AND,
        required=False
    )

    helper = FormHelper()
    helper.layout = Layout(
        Div(
            Div('server', css_class='span5'),
            Div('source', css_class='span5'),
            Div(InlineRadios('join_type'), css_class='span2'),

            Div(Field('filters', rows=2, css_class='span12'), css_class='span12'),
            Div(Field('groups', rows='1', css_class='span4'), css_class='span4'),
            Div(Field('aggregates', rows='1', css_class='span4'), css_class='span4'),
            Div(Field('json_path', rows='1', css_class='span4'), css_class='span4'),

            Div(MultiField(_('Result flattening'), Field('as_nested_list'), Field('as_dict_list')), css_class='span2'),
            Div(Field('renderer', rows='3', css_class='span1'), css_class='span1'),

            Div(Field('query_string', rows='3', css_class='span7'), css_class='span7'),

            Div(
                FormActions(
                    Submit('save_changes', _('Commit'), css_class="btn-primary"),
                    #Submit('clear', _('Clear')),
                ),
                css_class='span2'),
            css_class='controls controls-row'),
    )

    def capture_request(self, request):
        self.query = Query(None)
        self.query.parse_query(parse_request(request))

        initial = {
            'filters': u'&'.join(['%(field)s__%(filter_name)s=%(original_value)s' % filter for filter in self.query.filters]),
            'as_nested_list': self.query.as_nested_list,
            'as_dict_list': self.query.as_dict_list,
            'json_path': self.query.json_path,
            'join_type': self.query.join_type,
            'groups': u'&'.join(self.query.groups),
            'aggregates': u'&'.join(self.query.aggregates),
        }

        logger.debug('initial: %s' % initial)

        for field, value in initial.items():
            try:
                self.fields[field].initial = value
            except KeyError:
                pass

        self.fields['result'].initial = _('No results')

    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request')
        super(ClientForm, self).__init__(*args, **kwargs)
        self.fields['source'].queryset = Source.allowed.for_user(request.user)

        if self.is_valid():
            new_data = self.data.copy()
            new_data['query_string'] = self.compose_query_string()
            self.data = new_data

    def compose_query_string(self):
        cleaned_data = self.data
        result = []

        if cleaned_data.get('filters'):
            result.append(cleaned_data['filters'])

        if cleaned_data.get('groups'):
            result.append('_group_by=%s' % cleaned_data['groups'])

        if cleaned_data.get('aggregates'):
            for aggregate in cleaned_data['aggregates'].split(','):
                try:
                    result.append('_aggregate__%s=%s' % tuple(aggregate.split('=')))
                except TypeError:
                    pass

        if cleaned_data.get('json_path'):
            result.append('_json_path=%s' % cleaned_data['json_path'])

        if cleaned_data.get('as_nested_list'):
            result.append('_as_nested_list')

        if cleaned_data.get('as_dict_list'):
            result.append('_as_dict_list')

        result.append('_format=%s' % cleaned_data['renderer'])

        result.append('_join_type=%s' % JOIN_TYPES[int(cleaned_data['join_type'])])

        query_string = self.unescape_html('&'.join(result))

        if cleaned_data.get('source'):
            query_string = cleaned_data['server'] + reverse('source-get_all', args=[cleaned_data['source']]) + '?' + query_string
            if 'http://' not in cleaned_data['server']:
                query_string = 'http://' + query_string

        return query_string

    def unescape_html(self, string):
        return htmlparser.unescape(string).replace('%5B', '[').replace('%5D', ']')
コード例 #24
0
    def __init__(self, *args, **kwargs):
        super(InformeSemestralForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

        self.helper.form_show_labels = True
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-4'
        self.helper.field_class = 'col-sm-8'
        self.helper.form_action = "."

        self.helper.all().wrap(Field, css_class='input-sm')
        self.helper.filter_by_widget(forms.Textarea).wrap(
            Field, css_class="input-xlarge", rows="3")

        self.helper.layout = Layout(
            MultiField(
                '<b>Plantación*</b>',
                Div(
                    HTML(
                        '<p class="help-block">Cuantos proyectos misioneros o igleisas hijas fueron plantadas en el ultimo semestre</p>'
                    ),
                    Field('plantacion_nombre_1',
                          css_class='input-sm',
                          placeholder="nombre"),
                    Field('plantacion_lugar_1',
                          css_class='input-sm',
                          placeholder="lugar"),
                    Field('plantacion_fecha_1',
                          css_class='input-sm',
                          placeholder="mes/año"),
                    css_class='informe-semestral-plantacion clearfix',
                ),
                Div(
                    Field('plantacion_nombre_2',
                          css_class='input-sm',
                          placeholder="nombre"),
                    Field('plantacion_lugar_2',
                          css_class='input-sm',
                          placeholder="lugar"),
                    Field('plantacion_fecha_2',
                          css_class='input-sm',
                          placeholder="mes/año"),
                    css_class='informe-semestral-plantacion clearfix',
                ),
                Div(
                    Field('plantacion_nombre_3',
                          css_class='input-sm',
                          placeholder="nombre"),
                    Field('plantacion_lugar_3',
                          css_class='input-sm',
                          placeholder="lugar"),
                    Field('plantacion_fecha_3',
                          css_class='input-sm',
                          placeholder="mes/año"),
                    css_class='informe-semestral-plantacion clearfix',
                )), Field('miembros_actuales'), Field('nuevos_miembros'),
            Field('conversiones'), Field('bautismos_nuevos'),
            Field('no_bautismos'), Field('asistencia_general'),
            Field('ofrendas'), Field('plantacion'), Field('grupos_vida'),
            Field('asistencia_grupos'), Field('peticiones_oracion'),
            Field('testimonios'), Field('ministerio_ninos'),
            Field('uso_local'), Field('fotos'),
            FormActions(
                StrictButton('Enviar Informe',
                             type="Submit",
                             css_class="btn btn-success pull-right btn-md",
                             autocomplete="off"), ))
コード例 #25
0
    def __init__(self, *args, **kwargs):
        super(InformeSemestralPublicoForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal'

        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-9'

        self.helper.form_tag = False

        self.fields['fotos'].widget = AdminFileWidget()

        self.helper.layout = Layout(
            Fieldset(
                'Datos del Proyecto',
                Field('nombre_proyecto',
                      css_class='input-sm',
                      placeholder='nombre del proyecto'),
                Field('persona',
                      css_class='input-sm',
                      placeholder='persona encargada del proyecto'),
                Field('email', css_class='input-sm'),
                Field('telefono', css_class='input-sm'),
                Field('depto', css_class='input-sm'),
                Field('municipio', css_class='input-sm'),
                Field('direccion',
                      css_class="input-xlarge",
                      rows="2",
                      placeholder='dirección del proyecto'),
                Field('region', css_class='input-sm'),
            ),
            Fieldset(
                'Datos del Informe',
                Field('miembros_actuales',
                      css_class='input-sm',
                      placeholder='miembros actuales'),
                Field('nuevos_miembros',
                      css_class='input-sm',
                      placeholder='miembros nuevos'),
                Field('conversiones', css_class='input-sm'),
                Field('bautismos_nuevos', css_class='input-sm'),
                Field('no_bautismos', css_class='input-xlarge', rows="2"),
                Field('asistencia_general',
                      css_class="input-sm",
                      placeholder='asistencia general'),
            ),
            MultiField(
                '<b>Plantación*</b>',
                Div(
                    HTML(
                        u'<p class="help-block">Cuantos proyectos misioneros o iglesias hijas fueron plantadas desde el momento de la dedicación, si no hubo, de click en  <i class="fa fa-times"></i></p>'
                    ),
                    PrependedText('plantacion_nombre_1',
                                  "<i class='fa fa-times ninguno-btn'></i>",
                                  css_class="input-sm plantacion-field",
                                  placeholder="nombre"),
                    Field('plantacion_lugar_1',
                          css_class='input-sm',
                          placeholder="lugar"),
                    Field('plantacion_fecha_1',
                          css_class='input-sm',
                          placeholder="mes/año"),
                    css_class='col-sm-11 informe-semestral-plantacion clearfix',
                ),
                Div(
                    PrependedText('plantacion_nombre_2',
                                  "<i class='fa fa-times ninguno-btn' ></i>",
                                  css_class="input-sm",
                                  placeholder="nombre"),
                    Field('plantacion_lugar_2',
                          css_class='input-sm',
                          placeholder="lugar"),
                    Field('plantacion_fecha_2',
                          css_class='input-sm',
                          placeholder="mes/año"),
                    css_class='col-sm-11 informe-semestral-plantacion clearfix',
                ),
                Div(
                    PrependedText('plantacion_nombre_3',
                                  "<i class='fa fa-times ninguno-btn' ></i>",
                                  css_class="input-sm",
                                  placeholder="nombre"),
                    Field('plantacion_lugar_3',
                          css_class='input-sm',
                          placeholder="lugar"),
                    Field('plantacion_fecha_3',
                          css_class='input-sm',
                          placeholder="mes/año"),
                    css_class='col-sm-11 informe-semestral-plantacion clearfix',
                )),
            Field('grupos_vida',
                  css_class='input-sm',
                  placeholder='grupos de vida'),
            Field('asistencia_grupos', css_class='input-sm'),
            Field('ofrendas', css_class='input-sm'),
            Field('peticiones_oracion', css_class="input-xlarge", rows="3"),
            Field('testimonios', css_class="input-xlarge", rows="3"),
            Field('ministerio_ninos', css_class="input-xlarge", rows="3"),
            Field('uso_local', css_class="input-xlarge", rows="3"),
            'fotos',
        )