def test_alert(self):
     test_form = SampleForm()
     test_form.helper = FormHelper()
     test_form.helper.form_tag = False
     test_form.helper.layout = Layout(
         Alert(content="Testing...", css_class="alert-primary"),
         Alert(content="Testing...",
               css_class="alert-primary",
               dismiss=False),
     )
     assert parse_form(test_form) == parse_expected("alert.html")
Пример #2
0
    def __init__(self, *args, **kwargs):

        rows = [Div(
            to_column((
                to_row([
                    ('titulo', 8),
                    (Div(
                        css_class="g-recaptcha",
                        data_sitekey=settings.GOOGLE_RECAPTCHA_SITE_KEY
                    ), 4),
                    ('descricao', 12),
                    (Alert(_(
                        """<strong>Aviso</strong><br>
                            As manifestações registradas de maneira anônima são 
                            consideradas "Comunicações" e 
                            <strong class="text-red">não é possível o seu acompanhamento.</strong>
                            Caso deseje acompanhar o andamento 
                            da sua manifestação e receber uma resposta do órgão 
                            ou entidade, por favor identifique-se.
                            """),
                        css_class="alert-warning",
                        dismiss=False), 12)
                ]),
                12)),

            # to_column((
            #    to_row([('areatrabalho_parlamentar', 12)]),
            #    4)),

            css_class="row"
        )]

        if 'logged_user' in kwargs['initial'] and \
                kwargs['initial']['logged_user']:
            rows.insert(
                0, Alert(
                    _('<strong>Atenção, você foi desconectado!!!</strong><br>'
                      'Ao escolher fazer uma denúncia anônima, '
                      'o Portal da Câmara Municipal de Jataí desconectou seu '
                      'usuário para que sua manifestação não tenha nenhuma '
                      'relação com você. '
                      'Assim podemos garantir que sua denûncia é anônima '
                      'e não mantemos registro sobre você.<br>'
                      'Para voltar a utilizar das funções que você possuia '
                      'ao estar logado, é só se conectar novamente.'),
                    css_class="alert-info"))

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

        self.helper = FormHelper()
        self.helper.layout = SaplFormLayout(
            *rows,
            actions=form_actions(label=_('Enviar'))
        )
Пример #3
0
    def __init__(self, *args, **kwargs):

        rows = [
            Div(
                to_column((to_row([
                    ('titulo', 8),
                    (Div(css_class="g-recaptcha" if not settings.DEBUG else '',
                         data_sitekey=settings.GOOGLE_RECAPTCHA_SITE_KEY), 4),
                    ('descricao', 12),
                    (Alert(_("""<strong>Aviso</strong><br>
                            Ao enviar uma Denúncia Anônima, você receberá
                            um link para acompanhar sua denúncia.<br>
                            Só será
                            possível acompanhar e interagir com a ouvidoria
                            através deste link.<br>
                            Veja que este link será como um código 
                            privativo seu sem sua identificação, 
                            no entanto, se você compartilhar esse link, 
                            quem possuí-lo verá sua denúncia 
                            e poderá interagir também.
                            """),
                           css_class="alert-warning",
                           dismiss=False), 12)
                ]), 12)),

                # to_column((
                #    to_row([('areatrabalho_parlamentar', 12)]),
                #    4)),
                css_class="row")
        ]

        if 'logged_user' in kwargs['initial'] and \
                kwargs['initial']['logged_user']:
            rows.insert(
                0,
                Alert(_(
                    '<strong>Atenção, você foi desconectado!!!</strong><br>'
                    'Ao escolher fazer uma denúncia anônima, '
                    'o Portal da Câmara Municipal de Jataí desconectou seu '
                    'usuário para que sua manifestação não tenha nenhuma '
                    'relação com você. '
                    'Assim podemos garantir que sua denûncia é anônima '
                    'e não mantemos registro sobre você.<br>'
                    'Para voltar a utilizar das funções que você possuia '
                    'ao estar logado, é só se conectar novamente.'),
                      css_class="alert-info"))

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

        self.helper = FormHelper()
        self.helper.layout = SaplFormLayout(
            *rows, actions=form_actions(label=_('Enviar')))
Пример #4
0
    def __init__(self, *args, **kwargs):

        layout_form = Fieldset(
            VinculoDocDiarioOficial._meta.verbose_name,
            Row(
                to_column(('content_type', 3)),
                to_column(('tipo', 3)),
                to_column(('numero', 2)),
                to_column(('ano', 2)),
                to_column(('pagina', 2)),
                to_column(('diario', 0)),
            ),
            Alert('',
                  css_class="doc_selected hidden alert-info",
                  dismiss=False),
        )

        self.helper = SaplFormHelper()
        self.helper.layout = SaplFormLayout(layout_form)

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

        content_types = ContentType.objects.get_for_models(
            *models_with_gr_for_model(VinculoDocDiarioOficial))

        self.fields['content_type'].choices = [
            (ct.pk, ct) for k, ct in content_types.items()
        ]
        # Ordena por id
        self.fields['content_type'].choices.sort(key=lambda x: x[0])
Пример #5
0
    def __init__(self, *args, **kwargs):

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

        row_pwd = [
            to_row([('old_password', 12)]),
            to_row([('new_password1', 6), ('new_password2', 6)])
        ]

        row_pwd = []
        if self.instance.pwd_created:
            row_pwd.append(to_row([('old_password', 12)]))

        row_pwd += [to_row([('new_password1', 6), ('new_password2', 6)])]

        rows = to_row([
            (Fieldset(
                _('Cadastro Básico'),
                to_row([('first_name', 5), ('last_name', 4),
                        ('be_notified_by_email', 3), ('avatar', 7),
                        ('cropping', 5)])), 8),
            (Fieldset(
                _('Definição de senha'), *row_pwd,
                Alert(_('Após a definição e/ou alteração de senha, '
                        'sua tela será redirecionada para a tela de Login '
                        'para que você faça uma nova autenticação.'),
                      css_class="alert-info",
                      dismiss=False)), 4)
        ])

        self.helper = FormHelper()
        self.helper.layout = SaplFormLayout(*rows)

        if not self.instance.pwd_created:
            self.fields['old_password'].widget = forms.HiddenInput()
Пример #6
0
 def __init__(self):
     super(MonsterImportOptionsLayout, self).__init__(
         Div(
             HTML("""<h4 class="list-group-item-heading">Monster Filters</h4>"""),
             Alert(content="Note: If a monster is filtered out, it's equipped runes will not be imported either!", css_class='alert-warning'),
             Field('minimum_stars', template='crispy/button_radio_select.html'),
             Field('ignore_silver'),
             Field('ignore_material'),
             Field('except_with_runes'),
             Field('except_light_and_dark'),
             css_class='list-group-item',
         ),
         Div(
             HTML("""<h4 class="list-group-item-heading">Import Options</h4>"""),
             Field('default_priority'),
             Field('lock_monsters'),
             Field('missing_monster_action'),
             Field('missing_rune_action'),
             Div(
                 Field('clear_profile'),
                 css_class='alert alert-danger'
             ),
             css_class='list-group-item',
         ),
     )
Пример #7
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Alert(
             content=
             "<strong>Warning!</strong> Best check yo self, you're not looking too good.",
             css_class='alert-warning'),
         Fieldset(
             _('Main'),
             Row(
                 Column(AppendedText('subject', '$', active=True),
                        css_class='col-md-3'),
                 Column('description'),
             ),
         ),
         Fieldset(
             _('Second'),
             'tags',
             'persons',
             'status',
             'project',
         ),
         ButtonHolder(
             Button('submit',
                    'Save',
                    input_type='button',
                    css_class='btn-outline-primary'),
             Submit('submit', _('Save'), css_class='btn-outline-primary'),
             Reset('reset', _('Reset'), css_class='btn-outline-danger')),
     )
Пример #8
0
    def __init__(self, *args, **kwargs):

        layout = []

        row_publicacao = to_row([
            ('publicacao', 6),
            (InlineRadios('inconstitucionalidade'), 3),
        ])
        row_publicacao.fields.append(
            Alert(css_class='alert-info col-md-3',
                  content='<strong>%s</strong> %s' %
                  (_('Dica!'),
                   _('Inclua uma Nota de Dispositivo informando '
                     'sobre a Inconstitucionalidade.'))))
        layout.append(
            Fieldset(_('Registro de Publicação e Validade'),
                     row_publicacao,
                     css_class="col-md-12"))

        row_datas = to_row([
            ('inicio_vigencia', 3),
            ('fim_vigencia', 3),
            ('inicio_eficacia', 3),
            ('fim_eficacia', 3),
        ])
        layout.append(
            Fieldset(_('Datas de Controle de Vigência'),
                     row_datas,
                     css_class="col-md-12"))

        row_vigencia = Field(
            'dispositivo_vigencia',
            data_sapl_ta='DispositivoSearch',
            data_field='dispositivo_vigencia',
            data_type_selection='radio',
            template="compilacao/layout/dispositivo_radio.html")
        layout.append(
            Fieldset(_('Dispositivo de Vigência'),
                     to_row([(InlineRadios('extensao'), 12)]),
                     row_vigencia,
                     css_class="col-md-12"))

        self.helper = FormHelper()
        self.helper.layout = SaplFormLayout(
            *layout, label_cancel=_('Ir para o Editor Sequencial'))

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

        pubs = Publicacao.objects.order_by('-data', '-hora').filter(
            Q(ta=self.instance.ta) | Q(ta=self.instance.ta_publicado))
        self.fields['publicacao'].choices = [("", "---------")] + [
            (p.pk, _('%s realizada em %s. %s') %
             (p.tipo_publicacao, defaultfilters.date(
                 p.data, "d \d\e F \d\e Y"), str(p.ta))) for p in pubs
        ]

        dvs = Dispositivo.objects.order_by('ordem').filter(
            pk=self.instance.dispositivo_vigencia_id)
        self.fields['dispositivo_vigencia'].choices = [(d.pk, d) for d in dvs]
    def test_alert_block(self):
        test_form = SampleForm()
        test_form.helper = FormHelper()
        test_form.helper.layout = Layout(Alert(content="Testing...", block=True))
        html = render_crispy_form(test_form)

        assert html.count('<div class="alert alert-block"') == 1
        assert html.count("Testing...") == 1
Пример #10
0
    def __init__(self, *args, **kwargs):
        self.texto_articulado_proposicao = sapl.base.models.AppConfig.attr(
            'texto_articulado_proposicao')

        if not self.texto_articulado_proposicao:
            if 'tipo_texto' in self._meta.fields:
                self._meta.fields.remove('tipo_texto')
        else:
            if 'tipo_texto' not in self._meta.fields:
                self._meta.fields.append('tipo_texto')

        fields = [
            to_column((Fieldset(
                TipoProposicao._meta.verbose_name, Field('tipo')), 3)),
            Fieldset(_('Vincular a Matéria Legislativa Existente'),
                     to_column(('tipo_materia', 4)),
                     to_column(('numero_materia', 4)),
                     to_column(('ano_materia', 4))
                     ),

            to_column(
                (Alert('teste',
                       css_class="ementa_materia hidden alert-info",
                       dismiss=False), 12)),
            to_column(('descricao', 12)),
        ]

        if self.texto_articulado_proposicao:
            fields.append(
                to_column((InlineRadios('tipo_texto'), 5)),)

        fields.append(to_column((
            'texto_original', 7 if self.texto_articulado_proposicao else 12)))

        self.helper = FormHelper()
        self.helper.layout = SaplFormLayout(*fields)

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

        if self.instance.pk:
            self.fields['tipo_texto'].initial = ''
            if self.instance.texto_original:
                self.fields['tipo_texto'].initial = 'D'
            if self.texto_articulado_proposicao:
                if self.instance.texto_articulado.exists():
                    self.fields['tipo_texto'].initial = 'T'

            if self.instance.materia_de_vinculo:
                self.fields[
                    'tipo_materia'
                ].initial = self.instance.materia_de_vinculo.tipo
                self.fields[
                    'numero_materia'
                ].initial = self.instance.materia_de_vinculo.numero
                self.fields[
                    'ano_materia'
                ].initial = self.instance.materia_de_vinculo.ano
Пример #11
0
    def test_alert(self):
        test_form = SampleForm()
        test_form.helper = FormHelper()
        test_form.helper.layout = Layout(Alert(content="Testing..."))
        html = render_crispy_form(test_form)

        assert html.count('<div class="alert"') == 1
        assert html.count('<button type="button" class="close"') == 1
        assert html.count("Testing...") == 1
Пример #12
0
    def test_alert_block(self):
        test_form = TestForm()
        test_form.helper = FormHelper()
        test_form.helper.layout = Layout(
            Alert(content='Testing...', block=True))
        html = render_crispy_form(test_form)

        self.assertEqual(html.count('<div class="alert alert-block"'), 1)
        self.assertEqual(html.count('Testing...'), 1)
Пример #13
0
    def test_alert(self):
        test_form = TestForm()
        test_form.helper = FormHelper()
        test_form.helper.layout = Layout(Alert(content='Testing...'))
        html = render_crispy_form(test_form)

        self.assertEqual(html.count('<div class="alert"'), 1)
        self.assertEqual(html.count('<button type="button" class="close"'), 1)
        self.assertEqual(html.count('Testing...'), 1)
Пример #14
0
    def __init__(self, *args, **kwargs):

        row1 = to_row([('tipo_materia', 4), ('numero_paginas', 2),
                       ('tipo_autor', 3), ('autor', 3)])
        row2 = to_row([
            (InlineRadios('vincular_materia'), 3),
            ('numero_materia', 2),
            ('ano_materia', 2),
            (Div(), 1),
            (InlineRadios('data_hora_manual'), 4),
        ])
        row3 = to_row([
            (Div(), 2),
            (Alert("""
                Usuário: <strong>{}</strong> - {}<br> 
                IP: <strong>{}</strong> - {}<br>
                
                """.format(
                kwargs['initial']['user_data_hora_manual'],
                Protocolo._meta.get_field('user_data_hora_manual').help_text,
                kwargs['initial']['ip_data_hora_manual'],
                Protocolo._meta.get_field('ip_data_hora_manual').help_text,
            ),
                   dismiss=False,
                   css_class='alert-info'), 6),
            ('data', 2),
            ('hora', 2),
        ])
        row4 = to_row([('assunto_ementa', 12)])
        row5 = to_row([('observacao', 12)])
        row6 = to_row([('numero', 12)])

        fieldset = Fieldset(
            _('Protocolo com data e hora informados manualmente'),
            row3,
            css_id='protocolo_data_hora_manual')

        config = AppConfig.objects.first()
        if not config.protocolo_manual:
            row3 = to_row([(HTML("&nbsp;"), 12)])
            fieldset = row3

        self.helper = SaplFormHelper()
        self.helper.layout = Layout(
            Fieldset(_('Identificação da Matéria'), row1, row2), fieldset,
            row4, row5, HTML("&nbsp;"),
            Fieldset(
                _('Número do Protocolo (Apenas se quiser que a numeração comece'
                  ' a partir do número a ser informado)'), row6,
                HTML("&nbsp;"), form_actions(label=_('Protocolar Matéria'))))

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

        if not config.protocolo_manual:
            self.fields['data_hora_manual'].widget = forms.HiddenInput()
Пример #15
0
 def __init__(self, *args, **kwargs):
     super(ArriveForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper()
     self.helper.include_media = False
     self.helper.html5_required = True
     self.helper.form_class = 'col-sm-8'
     self.helper.layout = Layout(
         Div(Field('name', id="nomForm", autocomplete='off'),
             Field('matricule', id="matriculeForm", autocomplete='off'),
             css_class='form-inline'), Field('admission'),
         Field('datetime_arrive'), Hidden('type', 'nouveau'),
         Alert(
             content=
             "Un email sera envoyé aux différents responsables de l'élève.",
             css_class="alert-info"), Submit('submit', 'Soumettre'))
Пример #16
0
    def __init__(self, *args, **kwargs):

        rows = to_row(
            [
                (Div(
                    to_row([('titulo', 12),
                            ('descricao', 12),
                            (Div(
                                css_class="g-recaptcha",
                                data_sitekey=settings.GOOGLE_RECAPTCHA_SITE_KEY
                            ), 12)])
                ), 7),
                (Div(
                    to_row([('areatrabalho_parlamentar', 12)])
                ), 5),


            ]
        )

        if 'logged_user' in kwargs['initial'] and \
                kwargs['initial']['logged_user']:
            rows.insert(
                0, Alert(
                    _('<strong>Atenção, você foi desconectado!!!</strong><br>'
                      'Ao escolher fazer uma denúncia anônima, '
                      'o Portal da Câmara Municipal de Jataí desconectou seu '
                      'usuário para que sua manifestação não tenha nenhuma '
                      'relação com você. '
                      'Assim podemos garantir que sua denûncia é anônima '
                      'e não mantemos registro sobre você.<br>'
                      'Para voltar a utilizar das funções que você possuia '
                      'ao estar logado, é só se conectar novamente.'),
                    css_class="alert-info"))

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

        self.helper = FormHelper()
        self.helper.layout = SaplFormLayout(
            *rows,
            actions=form_actions(label=_('Enviar'))
        )
Пример #17
0
    def __init__(self, *args, **kwargs):
        super(RaceForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_class = 'form-horizontal'

        self.helper.layout = Layout(
            TabHolder(
                Tab('Pre-Race Information',
                    Div(Div(Field('season', autofocus=True),
                            css_class="col-md-3"),
                        Div(Field('title'), css_class="col-md-6"),
                        Div(Field('course'), css_class="col-md-3"),
                        css_class="row"),
                    Div(Div(Field('laps'), css_class="col-md-2"),
                        Div(Field('rowsize'), css_class="col-md-2"),
                        Div(Field('start'), css_class="col-md-2"),
                        Div(Field('shortname'), css_class="col-md-2"),
                        Div(Field('channel'), css_class="col-md-2"),
                        Div(Field('hashtag'), css_class="col-md-2"),
                        css_class="row"),
                    Div(Div(Field('url'), css_class="col-md-6"),
                        Div(Field('headerimgurl'), css_class="col-md-6"),
                        css_class="row"),
                    css_class="fade in"),
                Tab('Post-Race Statistics',
                    'urlrr',
                    Div(Div(AppendedText('duration', "seconds"),
                            css_class="col-md-4"),
                        Div(Field('yellowflags'), css_class="col-md-4"),
                        Div(Field('yellowlaps'), css_class="col-md-4"),
                        css_class="row"),
                    Div(Div(AppendedText('speedavg', "mph"),
                            css_class="col-md-3"),
                        Div(AppendedText('speedpole', "mph"),
                            css_class="col-md-3"),
                        Div(AppendedText('margin', "seconds"),
                            css_class="col-md-3"),
                        Div(Field('leadchanges'), css_class="col-md-3"),
                        css_class="row"),
                    css_class="fade"),
                Tab('Reddit Internals',
                    Alert(
                        content=
                        "<strong>Wait a second!</strong> &nbsp;Changing anything on this page could make IndyBot do some weird shit. &nbsp; So... &nbsp; Don't.",
                        css_class="alert-danger"),
                    Fieldset(
                        "Practice Thread",
                        Div(Div(Field('subpractice'), css_class="col-md-2"),
                            Div(Field('urlpractice'), css_class="col-md-10"),
                            css_class="row"),
                    ),
                    Fieldset(
                        "Race Thread",
                        Div(Div(Field('submission'), css_class="col-md-2"),
                            Div(Field('urlrace'), css_class="col-md-10"),
                            css_class="row"),
                    ),
                    Fieldset(
                        "Post-Race Thread",
                        Div(Div(Field('subpostrace'), css_class="col-md-2"),
                            Div(Field('urlpostrace'), css_class="col-md-10"),
                            css_class="row"),
                    ),
                    css_class="fade")),
            Submit('submit', u'Submit', css_class='btn btn-success'),
        )
Пример #18
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields["name"].widget.attrs["placeholder"] = "Full Name"
     self.fields["name"].widget.attrs["autocomplete"] = "off"
     self.fields["email"].widget.attrs["placeholder"] = "Email Address"
     self.fields["email"].widget.attrs["autocomplete"] = "off"
     self.fields["job_title"].widget.attrs["placeholder"] = "Job Title"
     self.fields["job_title"].widget.attrs["autocomplete"] = "off"
     self.fields["phone"].widget.attrs["placeholder"] = "Phone Number"
     self.fields["phone"].widget.attrs["autocomplete"] = "off"
     self.fields["note"].widget.attrs[
         "placeholder"] = "Brief Description of of the POC or a Note"
     self.helper = FormHelper()
     # Disable the <form> tags because this will be inside of an instance of `ClientForm()`
     self.helper.form_tag = False
     # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times
     self.helper.disable_csrf = True
     # Hide the field labels from the model
     self.helper.form_show_labels = False
     # Layout the form for Bootstrap
     self.helper.layout = Layout(
         # Wrap form in a div so Django renders form instances in their own element
         Div(
             # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms
             Alert(
                 content=("""
                     <strong>Contact Deleted!</strong>
                     Deletion will be permanent once the form is submitted. Click this alert to undo.
                     """),
                 css_class="alert alert-danger show formset-undo-button",
                 style="display:none; cursor:pointer;",
                 template="alert.html",
                 block=False,
                 dismiss=False,
             ),
             Div(
                 HTML("""
                     <h6>Contact #<span class="counter">{{ forloop.counter }}</span></h6>
                     <hr>
                     """),
                 Row(
                     Column("name", css_class="form-group col-md-6 mb-0"),
                     Column("job_title",
                            css_class="form-group col-md-6 mb-0"),
                     css_class="form-row",
                 ),
                 Row(
                     Column("email", css_class="form-group col-md-4 mb-0"),
                     Column("phone", css_class="form-group col-md-4 mb-0"),
                     Column("timezone",
                            css_class="form-group col-md-4 mb-0"),
                     css_class="form-row",
                 ),
                 "note",
                 Row(
                     Column(
                         Field("DELETE", style="display: none;"),
                         Button(
                             "formset-del-button",
                             "Delete Contact",
                             css_class=
                             "btn-sm btn-danger formset-del-button",
                         ),
                         css_class="form-group col-md-12 text-center",
                     ),
                     css_class="form-row",
                 ),
                 HTML("""
                     <p class="form-spacer"></p>
                     """),
                 css_class="formset",
             ),
             css_class="formset-container",
         ))
Пример #19
0
    def __init__(self, *args, **kwargs):

        self.proposicao_incorporacao_obrigatoria = \
            sapl.base.models.AppConfig.attr(
                'proposicao_incorporacao_obrigatoria')

        if self.proposicao_incorporacao_obrigatoria != 'C':
            if 'gerar_protocolo' in self._meta.fields:
                self._meta.fields.remove('gerar_protocolo')
        else:
            if 'gerar_protocolo' not in self._meta.fields:
                self._meta.fields.append('gerar_protocolo')

        if self.proposicao_incorporacao_obrigatoria == 'N':
            if 'numero_de_paginas' in self._meta.fields:
                self._meta.fields.remove('numero_de_paginas')
        else:
            if 'numero_de_paginas' not in self._meta.fields:
                self._meta.fields.append('numero_de_paginas')

        # esta chamada isola o __init__ de ProposicaoForm
        super(ProposicaoForm, self).__init__(*args, **kwargs)

        fields = [
            Fieldset(
                _('Dados Básicos'),
                to_column(('tipo_readonly', 4)),
                to_column(('data_envio', 3)),
                to_column(('autor_readonly', 5)),
                to_column(('descricao', 12)))]

        fields.append(
            Fieldset(_('Vinculado a Matéria Legislativa'),
                     to_column(('tipo_materia', 3)),
                     to_column(('numero_materia', 2)),
                     to_column(('ano_materia', 2)),
                     to_column(
                (Alert(_('O responsável pela incorporação pode '
                         'alterar a anexação. Limpar os campos '
                         'de Vinculação gera um %s independente '
                         'sem anexação se for possível para esta '
                         'Proposição. Não sendo, a rotina de incorporação '
                         'não permitirá estes campos serem vazios.'
                         ) % self.instance.tipo.content_type,
                       css_class="alert-info",
                       dismiss=False), 5)),
                to_column(
                (Alert('',
                       css_class="ementa_materia hidden alert-info",
                       dismiss=False), 12))))

        itens_incorporacao = [to_column(('regime_tramitacao', 4))]
        if self.proposicao_incorporacao_obrigatoria == 'C':
            itens_incorporacao.append(to_column((InlineRadios(
                'gerar_protocolo'), 4)))

        if self.proposicao_incorporacao_obrigatoria != 'N':
            itens_incorporacao.append(to_column(('numero_de_paginas', 4)))

        itens_incorporacao.append(to_column((FormActions(Submit(
            'incorporar', _('Incorporar'), css_class='pull-right')), 12)))

        fields.append(
            Fieldset(_('Registro de Incorporação'), *itens_incorporacao))

        fields.append(
            Fieldset(
                _('Registro de Devolução'),
                to_column(('justificativa_devolucao', 12)),
                to_column((FormActions(Submit(
                    'devolver', _('Devolver'),
                    css_class='btn-danger pull-right')), 12))
            ))
        self.helper = FormHelper()
        self.helper.layout = Layout(*fields)

        self.fields['tipo_readonly'].initial = self.instance.tipo.descricao
        self.fields['autor_readonly'].initial = str(self.instance.autor)

        if self.instance.materia_de_vinculo:
            self.fields[
                'tipo_materia'
            ].initial = self.instance.materia_de_vinculo.tipo
            self.fields[
                'numero_materia'
            ].initial = self.instance.materia_de_vinculo.numero
            self.fields[
                'ano_materia'
            ].initial = self.instance.materia_de_vinculo.ano

        if self.proposicao_incorporacao_obrigatoria == 'C':
            self.fields['gerar_protocolo'].initial = True
Пример #20
0
def SectionAlert(header, content):
    return Alert(
        dismiss=False,
        css_class='alert-info',
        content=('<h3>{}</h3> <p>{}</p>'.format(header, content)),
    )
Пример #21
0
 def __init__(self, *args, **kwargs):
     super(AuxServerAddressForm, self).__init__(*args, **kwargs)
     for field in self.fields:
         self.fields[field].widget.attrs["autocomplete"] = "chrome-off"
     self.fields["primary"].label = "Make Primary Address"
     self.fields["ip_address"].label = ""
     self.fields["ip_address"].widget.attrs["placeholder"] = "IP Address"
     self.fields["ip_address"].widget.attrs["autocomplete"] = "off"
     self.helper = FormHelper()
     # Disable the <form> tags because this will be inside of an instance of `ClientForm()`
     self.helper.form_tag = False
     # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times
     self.helper.disable_csrf = True
     # Hide the field labels from the model
     self.helper.form_show_labels = False
     # Layout the form for Bootstrap
     self.helper.layout = Layout(
         # Wrap form in a div so Django renders form instances in their own element
         Div(
             # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms
             Alert(
                 content=(
                     """
                     <strong>Address Deleted!</strong>
                     Deletion will be permanent once the form is submitted. Click this alert to undo.
                     """
                 ),
                 css_class="alert alert-danger show formset-undo-button",
                 style="display:none; cursor:pointer;",
                 template="alert.html",
                 block=False,
                 dismiss=False,
             ),
             Div(
                 HTML(
                     """
                     <p><strong>Address #<span class="counter">{{ forloop.counter }}</span></strong></p>
                     <hr>
                     """
                 ),
                 Row(
                     Column("ip_address", css_class="form-group col-md-6 mb-0"),
                     Column(
                         Field(
                             "primary",
                             css_class="primary-checkbox",
                             onchange="checkboxUpdate(this)",
                         ),
                         css_class="form-group col-md-6 mb-0",
                     ),
                     css_class="form-row",
                 ),
                 Row(
                     Column(
                         Field("DELETE", style="display: none;"),
                         Button(
                             "formset-del-button",
                             "Delete Address",
                             css_class="btn-sm btn-danger formset-del-button",
                         ),
                         css_class="form-group col-md-12 text-center",
                     ),
                     css_class="form-row",
                 ),
                 HTML(
                     """
                     <p class="form-spacer"></p>
                     """
                 ),
                 css_class="formset",
             ),
             css_class="formset-container",
         )
     )
Пример #22
0
 def __init__(self, *args, **kwargs):
     super(FollowUpForm, self).__init__(*args, **kwargs)
     self.helper = FormHelper(self)
     self.helper.form_class = 'form-horizontal'
     self.helper.label_class = 'col-sm-3 col-md-3 col-lg-3'
     self.helper.field_class = 'col-sm-9 col-md-9 col-lg-9'
     self.helper.layout = Layout(
         Div(Div(HTML(_('1. Familiarity')), css_class='panel-heading'),
             Div(HTML(
                 _("<p>How familiar are you with the case of {{ form.instance.case.name }} in the one year period after {{ form.instance.case.date_intervention }}?</p>"
                   )),
                 'familiarity',
                 HTML(
                     _("<p>Note: Even if you only have little or incomplete information, please try to answer all questions based on the knowledge you have.</p>"
                       )),
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('2. Development of the situation')),
                 css_class='panel-heading'),
             Div(HTML(
                 _("<p>How would you describe the development of the case of {{ form.instance.case.name }} in the one year period after {{ form.instance.case.date_intervention }}, in light of the incidents listed above that occurred before the action of the Special Rapporteur?</p>"
                   )),
                 HTML(
                     _("<p>We recommend you look at <a data-toggle='modal' data-target='#myModal'>this table</a> to ensure consistency in responses. The table lists various examples and explains how to rate developments of a case depending on the initial situation.</p>"
                       )),
                 'rating',
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('3. Significant incidents')),
                 css_class='panel-heading'),
             Div(HTML(
                 _("<p>Please list all known significant incidents that occurred in the one year period after {{ form.instance.case.date_intervention }}. If there were more than 5, please concentrate on the most important ones:</p>"
                   )),
                 TabHolder(
                     Tab(_('Incident #1'), 'incident_date_1',
                         'incident_text_1'),
                     Tab(
                         _('Incident #2'),
                         'incident_date_2',
                         'incident_text_2',
                     ),
                     Tab(
                         _('Incident #3'),
                         'incident_date_3',
                         'incident_text_3',
                     ),
                     Tab(
                         _('Incident #4'),
                         'incident_date_4',
                         'incident_text_4',
                     ),
                     Tab(
                         _('Incident #5'),
                         'incident_date_5',
                         'incident_text_5',
                     ),
                 ),
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('4. International attention')),
                 css_class='panel-heading'),
             Div(HTML(
                 _("<p>Do you believe that the international attention given to the case of {{ form.instance.case.name }} had an impact on the development of his/her situation in the one year period after {{ form.instance.case.date_intervention }}?</p>"
                   )),
                 'attention',
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('5. Special Rapporteur\'s intervention')),
                 css_class='panel-heading'),
             Div(HTML(
                 _("<p>Do you believe that the intervention of the Special Rapporteur had a distinguishable impact on this case (amidst broader international attention)?</p>"
                   )),
                 'intervention',
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('6. Impact of the attention')),
                 css_class='panel-heading'),
             Div(HTML(
                 _('<p>Please provide as much detail as possible on what makes you come to your conclusion on question (4) and (5), as well as on what kind of impact the attention had (if any):</p>'
                   )),
                 'impact',
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('7. Further comments/feedback')),
                 css_class='panel-heading'),
             Div('further_comments', css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('8. Voluntary contact information')),
                 css_class='panel-heading'),
             Div('want_informed',
                 'contact_again',
                 'email_address',
                 css_class='panel-body'),
             css_class='panel panel-info'),
         Div(Div(HTML(_('Submission')), css_class='panel-heading'),
             Div(Alert(content=_(
                 '<strong>Warning!</strong> You can only submit this form once. After your submission the link will be deactivated.'
             ),
                       css_class="alert-danger"),
                 HTML(_("<p>Thank you for your contribution!</p>")),
                 StrictButton(_(
                     'Submit <span class="glyphicon glyphicon-envelope"></span>'
                 ),
                              type='submit',
                              name='save',
                              css_class="btn-primary"),
                 css_class='panel-body'),
             css_class='panel panel-primary'),
     )
Пример #23
0
 def __init__(self, *args, **kwargs):
     super(ProjectTargetForm, self).__init__(*args, **kwargs)
     for field in self.fields:
         self.fields[field].widget.attrs["autocomplete"] = "off"
     self.fields["ip_address"].widget.attrs["placeholder"] = "IP Address"
     self.fields["hostname"].widget.attrs["placeholder"] = "FQDN"
     self.fields["note"].widget.attrs["rows"] = 5
     self.fields["note"].widget.attrs["placeholder"] = "Brief Description or Note"
     self.helper = FormHelper()
     # Disable the <form> tags because this will be inside an instance of `ProjectForm()`
     self.helper.form_tag = False
     # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times
     self.helper.disable_csrf = True
     # Hide the field labels from the model
     self.helper.form_show_labels = False
     # Layout the form for Bootstrap
     self.helper.layout = Layout(
         # Wrap form in a div so Django renders form instances in their own element
         Div(
             # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms
             Alert(
                 content=(
                     """
                     <strong>Target Deleted!</strong>
                     Deletion will be permanent once the form is submitted. Click this alert to undo.
                     """
                 ),
                 css_class="alert alert-danger show formset-undo-button",
                 style="display:none; cursor:pointer;",
                 template="alert.html",
                 block=False,
                 dismiss=False,
             ),
             Div(
                 HTML(
                     """
                     <h6>Target #<span class="counter">{{ forloop.counter }}</span></h6>
                     <hr>
                     """
                 ),
                 Row(
                     Column("ip_address", css_class="col-md-6"),
                     Column("hostname", css_class="col-md-6"),
                 ),
                 "note",
                 Row(
                     Column(
                         Button(
                             "formset-del-button",
                             "Delete Target",
                             css_class="btn-sm btn-danger formset-del-button",
                         ),
                         css_class="form-group col-md-4 offset-md-4",
                     ),
                     Column(
                         Field("DELETE", style="display: none;"),
                         css_class="form-group col-md-4 text-center",
                     ),
                     css_class="form-row",
                 ),
                 css_class="formset",
             ),
             css_class="formset-container",
         )
     )
Пример #24
0
 def __init__(self, *args, **kwargs):
     super(ProjectObjectiveForm, self).__init__(*args, **kwargs)
     self.fields["deadline"].widget.attrs["placeholder"] = "mm/dd/yyyy"
     self.fields["deadline"].widget.attrs["autocomplete"] = "off"
     self.fields["deadline"].widget.input_type = "date"
     self.fields["objective"].widget.attrs["rows"] = 5
     self.fields["objective"].widget.attrs["placeholder"] = "High-Level Objective"
     self.fields["description"].widget.attrs["placeholder"] = "Description, Notes, and Context"
     self.fields["priority"].empty_label = "-- Prioritize Objective --"
     self.helper = FormHelper()
     # Disable the <form> tags because this will be inside an instance of `ProjectForm()`
     self.helper.form_tag = False
     # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times
     self.helper.disable_csrf = True
     # Hide the field labels from the model
     self.helper.form_show_labels = False
     # Layout the form for Bootstrap
     self.helper.layout = Layout(
         # Wrap form in a div so Django renders form instances in their own element
         Div(
             # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms
             Alert(
                 content=(
                     """
                     <strong>Objective Deleted!</strong>
                     Deletion will be permanent once the form is submitted. Click this alert to undo.
                     """
                 ),
                 css_class="alert alert-danger show formset-undo-button",
                 style="display:none; cursor:pointer;",
                 template="alert.html",
                 block=False,
                 dismiss=False,
             ),
             Div(
                 HTML(
                     """
                     <h6>Objective #<span class="counter">{{ forloop.counter }}</span></h6>
                     <hr>
                     """
                 ),
                 Row(
                     Column("objective", css_class="col-md-6"),
                     Column(
                         FieldWithButtons(
                             "deadline",
                             HTML(
                                 """
                                 <button
                                     class="btn btn-secondary"
                                     type="button"
                                     onclick="copyEndDate($(this).closest('div').find('input'))"
                                 >
                                 Copy
                                 </button>
                                 """
                             ),
                         ),
                         css_class="col-md-6",
                     ),
                 ),
                 Row(
                     Column(
                         Field("status", css_class="form-select"),
                         css_class="col-md-6",
                     ),
                     Column(
                         Field("priority", css_class="form-select"),
                         css_class="col-md-6",
                     ),
                 ),
                 "description",
                 Row(
                     Column(
                         SwitchToggle(
                             "complete",
                         ),
                         css_class="col-md-4",
                     ),
                     Column(
                         Button(
                             "formset-del-button",
                             "Delete Objective",
                             css_class="btn-sm btn-danger formset-del-button",
                         ),
                         css_class="form-group col-md-4",
                     ),
                     Column(
                         Field("DELETE", style="display: none;"),
                         css_class="form-group col-md-4 text-center",
                     ),
                     css_class="form-row",
                 ),
                 css_class="formset",
             ),
             css_class="formset-container",
         )
     )
Пример #25
0
 def __init__(self, *args, **kwargs):
     super(ProjectAssignmentForm, self).__init__(*args, **kwargs)
     self.fields["operator"].queryset = self.fields["operator"].queryset.order_by(
         "-is_active", "username", "name"
     )
     self.fields["operator"].label_from_instance = lambda obj: obj.get_display_name
     self.fields["start_date"].widget.attrs["placeholder"] = "mm/dd/yyyy"
     self.fields["start_date"].widget.attrs["autocomplete"] = "off"
     self.fields["start_date"].widget.input_type = "date"
     self.fields["end_date"].widget.attrs["placeholder"] = "mm/dd/yyyy"
     self.fields["end_date"].widget.attrs["autocomplete"] = "off"
     self.fields["end_date"].widget.input_type = "date"
     self.fields["note"].widget.attrs["rows"] = 5
     self.fields["note"].widget.attrs["placeholder"] = "Additional Information or Notes"
     self.helper = FormHelper()
     # Disable the <form> tags because this will be inside an instance of `ProjectForm()`
     self.helper.form_tag = False
     # Disable CSRF so `csrfmiddlewaretoken` is not rendered multiple times
     self.helper.disable_csrf = True
     # Hide the field labels from the model
     self.helper.form_show_labels = False
     # Layout the form for Bootstrap
     self.helper.layout = Layout(
         # Wrap form in a div so Django renders form instances in their own element
         Div(
             # These Bootstrap alerts begin hidden and function as undo buttons for deleted forms
             Alert(
                 content=(
                     """
                     <strong>Assignment Deleted!</strong>
                     Deletion will be permanent once the form is submitted. Click this alert to undo.
                     """
                 ),
                 css_class="alert alert-danger show formset-undo-button",
                 style="display:none; cursor:pointer;",
                 template="alert.html",
                 block=False,
                 dismiss=False,
             ),
             Div(
                 HTML(
                     """
                     <h6>Assignment #<span class="counter">{{ forloop.counter }}</span></h6>
                     <hr>
                     """
                 ),
                 Row(
                     Column("operator", css_class="form-group col-md-6 mb-0"),
                     Column("role", css_class="form-group col-md-6 mb-0"),
                     css_class="form-row",
                 ),
                 Row(
                     Column(
                         FieldWithButtons(
                             "start_date",
                             HTML(
                                 """
                                 <button
                                     class="btn btn-secondary"
                                     type="button"
                                     onclick="copyStartDate($(this).closest('div').find('input'))"
                                 >
                                 Copy
                                 </button>
                                 """
                             ),
                         ),
                         css_class="form-group col-md-6 mb-0",
                     ),
                     Column(
                         FieldWithButtons(
                             "end_date",
                             HTML(
                                 """
                             <button
                                 class="btn btn-secondary"
                                 type="button"
                                 onclick="copyEndDate($(this).closest('div').find('input'))"
                             >
                             Copy
                             </button>
                             """
                             ),
                         ),
                         css_class="form-group col-md-6 mb-0",
                     ),
                 ),
                 "note",
                 Row(
                     Column(
                         Button(
                             "formset-del-button",
                             "Delete Assignment",
                             css_class="btn-sm btn-danger formset-del-button",
                         ),
                         css_class="form-group col-md-4 offset-md-4",
                     ),
                     Column(
                         Field("DELETE", style="display: none;"),
                         css_class="form-group col-md-4 text-center",
                     ),
                     css_class="form-row",
                 ),
                 css_class="formset",
             ),
             css_class="formset-container",
         ),
     )
Пример #26
0
    def __init__(self,
                 *args,
                 workshop_url,
                 has_perm_to_edit=True,
                 has_perm_to_disable_uploads=False,
                 profile_warnings=None,
                 **kwargs):
        super(ModelForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.include_media = False

        # Disable fields that should be disabled
        if not self.instance.is_workshop_editable() or not has_perm_to_edit:
            for field in self.fields.values():
                field.disabled = True

        if self.instance.status:
            # The proposition cannot be edited once the workshop has a status set
            self.fields['proposition_description'].disabled = True

        if not has_perm_to_disable_uploads:
            self.fields['solution_uploads_enabled'].disabled = True

        # Make sure only current category and type choices are displayed
        if self.instance is None:
            raise ValueError(
                'WorkshopForm must be provided with an instance with the .year field already set'
            )
        year = self.instance.year
        self.fields['category'].queryset = WorkshopCategory.objects.filter(
            year=year)
        self.fields['type'].queryset = WorkshopType.objects.filter(year=year)

        # Display link to current qualification tasks:
        if self.instance.qualification_problems:
            self.fields['qualification_problems'].help_text = format_html(
                'Aktualnie: <a href="{}" target="_blank">{}</a>',
                reverse('qualification_problems',
                        args=[self.instance.year.pk, self.instance.name]),
                os.path.basename(self.instance.qualification_problems.path))
        else:
            self.fields['qualification_problems'].help_text = 'Aktualnie: brak'

        # Configure TinyMCE settings
        mce_attrs = {}
        mce_attrs['readonly'] = self.fields[
            'proposition_description'].disabled  # does not seem to respect the Django field settings for some reason
        self.fields['proposition_description'].widget = InitializedTinyMCE(
            mce_attrs=mce_attrs)

        mce_attrs = settings.TINYMCE_DEFAULT_CONFIG_WITH_IMAGES.copy()
        if self.instance and self.instance.pk:
            mce_attrs['automatic_uploads'] = True
            mce_attrs['images_upload_url'] = reverse('workshop_edit_upload',
                                                     kwargs={
                                                         'year':
                                                         self.instance.year.pk,
                                                         'name':
                                                         self.instance.name
                                                     })
        mce_attrs['readonly'] = self.fields[
            'page_content'].disabled  # does not seem to respect the Django field settings for some reason
        self.fields['page_content'].widget = InitializedTinyMCE(
            mce_attrs=mce_attrs)

        # Layout
        self.fieldset_general = Fieldset(
            "Ogólne",
            Div(Div(PrependedAppendedText(
                'name',
                workshop_url[0] + '<b>' + str(year.pk) + '</b>' +
                workshop_url[1],
                workshop_url[2],
                template=
                "%s/layout/prepended_appended_text_with_mobile_support.html"),
                    css_class='col-lg-12'),
                Div('title', css_class='col-lg-12'),
                css_class='row'),
            Div(Div('type', css_class='col-lg-6'),
                Div('category', css_class='col-lg-6'),
                css_class='row'),
        )
        if profile_warnings:
            for message in profile_warnings:
                self.fieldset_general.fields.append(
                    Alert(content=message,
                          dismiss=False,
                          css_class='alert-info'))
        self.fieldset_proposal = Fieldset(
            "Opis propozycji",
            'proposition_description',
        )
        self.fieldset_qualification = Fieldset(
            "Kwalifikacja",
            'is_qualifying',
            Div('qualification_problems',
                Div(Div('max_points', css_class='col-lg-6'),
                    Div('qualification_threshold', css_class='col-lg-6'),
                    css_class='row'),
                'solution_uploads_enabled',
                css_id='qualification_settings'),
        )
        self.fieldset_public_page = Fieldset("Strona warsztatów",
                                             'short_description',
                                             'page_content',
                                             'page_content_is_public')
        self.fieldset_submit = FormActions(
            StrictButton(
                'Zapisz' if self.instance and self.instance.pk else 'Zgłoś!',
                type='submit',
                css_class='btn-outline-primary btn-lg mx-1 my-3'),
            css_class='text-right',
        )

        if not self.instance or not self.instance.is_publicly_visible():
            for field in [
                    'qualification_problems', 'is_qualifying',
                    'solution_uploads_enabled', 'max_points',
                    'qualification_threshold', 'short_description',
                    'page_content', 'page_content_is_public'
            ]:
                del self.fields[field]

            self.helper.layout = Layout(
                self.fieldset_general,
                self.fieldset_proposal,
                self.fieldset_submit,
            )
        else:
            if not has_perm_to_edit:
                self.helper.layout = Layout(
                    self.fieldset_general,
                    self.fieldset_proposal,
                    self.fieldset_qualification,
                    self.fieldset_public_page,
                )
            else:
                self.helper.layout = Layout(
                    self.fieldset_general,
                    self.fieldset_proposal,
                    self.fieldset_qualification,
                    self.fieldset_public_page,
                    self.fieldset_submit,
                )