class StyledForm(forms.Form): def __init__(self, *args, **kwargs): # type: (...) -> None from crispy_forms.helper import FormHelper self.helper = FormHelper() self._configure_helper() super(StyledForm, self).__init__(*args, **kwargs) def _configure_helper(self): # type: () -> None self.helper.form_class = "form-horizontal" self.helper.label_class = "col-lg-2" self.helper.field_class = "col-lg-8" def style_codemirror_widget(self): from codemirror import CodeMirrorTextarea from crispy_forms.layout import Div if self.helper.layout is None: from crispy_forms.helper import FormHelper self.helper = FormHelper(self) self._configure_helper() self.helper.filter_by_widget(CodeMirrorTextarea).wrap( Div, css_class="relate-codemirror-container")
class StyledForm(forms.Form): def __init__(self, *args, **kwargs): # type: (...) -> None from crispy_forms.helper import FormHelper self.helper = FormHelper() self._configure_helper() super(StyledForm, self).__init__(*args, **kwargs) def _configure_helper(self): # type: () -> None self.helper.form_class = "form-horizontal" self.helper.label_class = "col-lg-2" self.helper.field_class = "col-lg-8" def style_codemirror_widget(self): from codemirror import CodeMirrorTextarea from crispy_forms.layout import Div if self.helper.layout is None: from crispy_forms.helper import FormHelper self.helper = FormHelper(self) self._configure_helper() self.helper.filter_by_widget(CodeMirrorTextarea).wrap( Div, css_class="relate-codemirror-container")
class EdificacionForm(ModelFormBase): class Meta: model = Edificacion exclude = [ 'estado', 'usuario', 'etapa_actual', 'ingeniero', 'arquitecto', 'tesorero', 'aprobacion_regional', 'aprobacion_arquitecto', 'aprobacion_ingeniero', 'aprobacion_nacional', 'aprobacion_tesorero', 'created', 'updated', 'requiere_arquitecto', 'aprobacion_internacional', 'usuarios_asignados', 'planos_creados', 'aprobacion_fotos', 'envio_icm', 'envio_alianza', 'fecha_aprox_dedicacion' ] def __init__(self, *args, **kwargs): super(EdificacionForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.fields['coordenadas'].widget = map_widgets.MapsGeoPointhWidget() #Esta es una manera mas sencilla de agregar atributos a los campos self.helper.all().wrap(Field, css_class='input-sm') self.helper['direccion'].wrap(Field, css_class="input-xlarge", rows="2") self.helper['coordenadas'].wrap(Field, css_class="geolocation_field") self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
class InformacionFinancieraForm(ModelFormBase): class Meta: model = InformacionFinanciera exclude = ['edificacion'] def __init__(self, *args, **kwargs): super(InformacionFinancieraForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.helper.all().wrap(Field, css_class='input-sm') self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
class CondicionesForm(ModelFormBase): class Meta: model = Condiciones exclude = ['edificacion'] def __init__(self, *args, **kwargs): super(CondicionesForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.label_class = 'col-sm-4' self.helper.field_class = 'col-sm-8' self.helper.all().wrap(Field, css_class='input-sm') self.helper.filter_by_widget(forms.Select).wrap(InlineRadios) self.helper.filter_by_widget(forms.Textarea).wrap( Field, css_class="input-xlarge", rows="4")
class InformacionFinancieraForm(ModelFormBase): class Meta: model = InformacionFinanciera exclude = ['edificacion'] def __init__(self, *args, **kwargs): super(InformacionFinancieraForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.helper.all().wrap(Field, css_class='input-sm') self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
class CondicionesForm(ModelFormBase): class Meta: model = Condiciones exclude = ['edificacion'] def __init__(self, *args, **kwargs): super(CondicionesForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.label_class = 'col-sm-4' self.helper.field_class = 'col-sm-8' self.helper.all().wrap(Field, css_class='input-sm') self.helper.filter_by_widget(forms.Select).wrap(InlineRadios) self.helper.filter_by_widget(forms.Textarea).wrap(Field, css_class="input-xlarge", rows="4")
class CongregacionForm(ModelFormBase): class Meta: model = Congregacion exclude = ['edificacion'] def __init__(self, *args, **kwargs): super(CongregacionForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.fields['fecha_fundacion'].widget = SelectDateWidget( years=(range(1900, date.today().year + 1))) self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.fields['titulos_obtenidos'].widget = forms.TextInput( attrs={'placeholder': 'Tecnico en Biblia, Master en Biblia'}) self.helper.all().wrap(Field, css_class='input-sm') self.helper.filter_by_widget(forms.Textarea).wrap( Field, css_class="input-xlarge", rows="2") self.helper.filter_by_widget(SelectDateWidget).wrap( Field, css_class="input-sm", style="width:110px; float:left; margin-right:5px;") self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
class CrispyFormMixin(object): """ Mixin that adds a helper property to the form. """ @property def helper(self): if not hasattr(self, '_helper'): self._helper = FormHelper(form=self) self._helper.form_tag = False self.set_layout() self._helper.filter_by_widget(forms.TimeInput).wrap( Field, data_provide="datepicker", data_date_pickDate="false") self._helper.filter_by_widget(forms.DateInput).wrap( Field, data_provide="datepicker", data_date_pickTime="false", data_date_format="YYYY-MM-DD" ) return self._helper def set_layout(self): """ Update this method if you want a custom layout. """ pass
class EdificacionForm(ModelFormBase): class Meta: model = Edificacion exclude = ['estado', 'usuario', 'etapa_actual', 'ingeniero', 'arquitecto', 'tesorero', 'aprobacion_regional', 'aprobacion_arquitecto', 'aprobacion_ingeniero', 'aprobacion_nacional', 'aprobacion_tesorero', 'created', 'updated', 'requiere_arquitecto','aprobacion_internacional', 'usuarios_asignados', 'planos_creados','aprobacion_fotos','envio_icm','envio_alianza','fecha_aprox_dedicacion'] def __init__(self, *args, **kwargs): super(EdificacionForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.fields['coordenadas'].widget = map_widgets.MapsGeoPointhWidget() #Esta es una manera mas sencilla de agregar atributos a los campos self.helper.all().wrap(Field, css_class='input-sm') self.helper['direccion'].wrap(Field, css_class="input-xlarge", rows="2") self.helper['coordenadas'].wrap(Field, css_class="geolocation_field") self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
class CongregacionForm(ModelFormBase): class Meta: model = Congregacion exclude = ['edificacion'] def __init__(self, *args, **kwargs): super(CongregacionForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.fields['fecha_fundacion'].widget = SelectDateWidget(years=( range(1900, date.today().year + 1) ) ) self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.fields['titulos_obtenidos'].widget = forms.TextInput(attrs={'placeholder': 'Tecnico en Biblia, Master en Biblia'}) self.helper.all().wrap(Field, css_class='input-sm') self.helper.filter_by_widget(forms.Textarea).wrap(Field, css_class="input-xlarge", rows="2") self.helper.filter_by_widget(SelectDateWidget).wrap(Field, css_class="input-sm", style="width:110px; float:left; margin-right:5px;") self.helper.filter_by_widget(forms.Select).wrap(InlineRadios)
class BaseApplicationForm(forms.Form): """ Given a dict of parameters describing the required fields for this application, constructs a suitable application form. Expected dict format: { 'user': [list, of, required, user, data, fields], 'partner_1': [list, of, required, fields, for, partner, 1], 'partner_2': [list, of, required, fields, for, partner, 2], (additional partners as needed) } 'user' is mandatory. 'partner_1' is mandatory. Additional partners are optional. See https://django-crispy-forms.readthedocs.org/ for information on form layout. """ def __init__(self, *args, **kwargs): self._validate_parameters(**kwargs) self.field_params = kwargs.pop('field_params') super(BaseApplicationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self._initialize_form_helper() self.helper.layout = Layout() user_data = self.field_params.pop('user') self._add_user_data_subform(user_data) # For each partner, build a partner data section of the form. for partner in self.field_params: self._add_partner_data_subform(partner) # Make sure to align any checkbox inputs with other field types self.helper.filter_by_widget(forms.CheckboxInput).wrap( Div, css_class= "col-sm-8 col-sm-offset-4 col-md-9 col-md-offset-3 apply-tos") self.helper.add_input( Submit( 'submit', # Translators: Labels the button users click to apply for a partner's resources. _('Apply'), css_class='center-block')) def _get_partner_object(self, partner): # Extract the number component of (e.g.) 'partner_1'. try: partner_id = partner[8:] # Verify that it is the ID number of a real partner. partner = Partner.objects.get(id=partner_id) return partner except Partner.DoesNotExist: logger.exception('BaseApplicationForm received a partner ID that ' 'did not match any partner in the database') raise def _validate_parameters(self, **kwargs): """ Ensure that parameters have been passed in and match the format specified in the docstring. """ try: field_params = kwargs['field_params'] except KeyError: logger.exception('Tried to instantiate a BaseApplicationForm but ' 'did not have field_params') raise try: assert 'user' in field_params except AssertionError: logger.exception('Tried to instantiate a BaseApplicationForm but ' 'there was no user parameter in field_params') raise try: # We should have 'user' plus at least one partner in the keys. assert len(field_params.keys()) >= 2 except AssertionError: logger.exception( 'Tried to instantiate a BaseApplicationForm but ' 'there was not enough information in field_params') raise expected = re.compile(r'partner_\d+') for key in field_params.keys(): # All keys which are not the user data should be partner data. if key != 'user': try: assert expected.match(key) except AssertionError: logger.exception( 'Tried to instantiate a BaseApplicationForm but ' 'there was a key that did not match any expected values' ) def _validate_user_data(self, user_data): try: assert (set(user_data) <= set(USER_FORM_FIELDS)) except AssertionError: logger.exception('BaseApplicationForm received invalid user data') raise def _validate_partner_data(self, partner_data): try: assert (set(partner_data) <= set(PARTNER_FORM_OPTIONAL_FIELDS)) except AssertionError: logger.exception( 'BaseApplicationForm received invalid partner data') raise def _initialize_form_helper(self): # Add basic styling to the form. self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-xs-12 col-sm-4 col-md-3' self.helper.field_class = 'col-xs-12 col-sm-8 col-md-9' def _add_user_data_subform(self, user_data): self._validate_user_data(user_data) if user_data: # Translators: This labels a section of a form where we ask users to enter personal information (such as their country of residence) when making an application. user_data_layout = Fieldset(_('About you')) for datum in user_data: self.fields[datum] = FIELD_TYPES[datum] self.fields[datum].label = FIELD_LABELS[datum] # Show which partner wants which personal data if applying # for more than one. if len(self.field_params) > 1: # Translators: This text is shown in the application form under each piece of personal information requested. {partner_list} will be a list of 2 or more organisations that require this personal data, and should not be translated. self.fields[datum].help_text = _( "Requested by: {partner_list}".format( partner_list=", ".join(user_data[datum])).decode( 'utf-8')) user_data_layout.append(datum) self.helper.layout.append(user_data_layout) # Translators: This this note appears in a section of a form where we ask users to enter info (like country of residence) when applying for resource access. self.helper.layout.append( HTML( _('<p><small><i>Your personal data ' 'will be processed according to our <a href="{terms_url}">' 'privacy policy</a>.</i></small></p>'.format( terms_url=reverse('terms'))))) def _add_partner_data_subform(self, partner): partner_data = self.field_params[partner] partner_object = self._get_partner_object(partner) partner_layout = Fieldset( # Translators: This is the title of the application form page, where users enter information required for the application. It lets the user know which partner application they are entering data for. {partner} _('Your application to {partner}').format(partner=partner_object)) self._validate_partner_data(partner_data) # partner_data lists the optional fields required by that partner; # base fields should be in the form for all partners. all_partner_data = partner_data + PARTNER_FORM_BASE_FIELDS if all_partner_data: for datum in all_partner_data: # This will yield fields with names like 'partner_1_occupation'. # This will let us tell during form processing which fields # belong to which partners. field_name = '{partner}_{datum}'.format(partner=partner, datum=datum) self.fields[field_name] = FIELD_TYPES[datum] self.fields[field_name].label = FIELD_LABELS[datum] if datum == AGREEMENT_WITH_TERMS_OF_USE: # Make sure that, if the partner requires agreement with # terms of use, that link is provided inline. help_text = '<a href="{url}">{url}</a>'.format( url=partner_object.terms_of_use) self.fields[field_name].help_text = help_text if datum == SPECIFIC_STREAM: # Only show streams for this partner partner_id = int(partner[8:]) specific_stream = forms.ModelChoiceField( queryset=Stream.objects.filter(partner_id=partner_id)) self.fields[field_name] = specific_stream self.fields[field_name].label = FIELD_LABELS[datum] if datum == ACCOUNT_EMAIL: # If partner requires pre-registration, make sure users # get a link where they can sign up. # Translators: For some applications, users must register at another website before finishing the application form, and must then enter their email address used when registering. help_text = _( 'You must register at <a href="{url}">{url}</a> ' 'before applying.').format( url=partner_object.registration_url) self.fields[field_name].help_text = help_text partner_layout.append(field_name) self.helper.layout.append(partner_layout)
class MechanicalInputForm(forms.ModelForm): """ Form for mechanical input """ Bs_t = forms.FloatField(label='Bs (t)', label_suffix='MPa', help_text='Constante de tensión de Byerlee', widget=forms.NumberInput(attrs={'step': '5e3'}), min_value=0, max_value=1e5) Bs_c = forms.FloatField(label='Bs (c)', label_suffix='MPa', help_text='Constante de compresión de Byerlee', widget=forms.NumberInput(attrs={'step': '5e3'}), min_value=-1e5, max_value=-1e3) e = forms.FloatField(label='ė', label_suffix='s⁻¹', help_text='Strain Rate', widget=forms.NumberInput(attrs={'step': '5e-16'}), min_value=0, max_value=1e-14) R = forms.FloatField(label='R', label_suffix='J·mol⁻¹·K⁻¹', help_text='Constante universal de gases', widget=forms.NumberInput(attrs={'step': '1e-2'}), min_value=1, max_value=10) s_max = forms.FloatField(label='σ max.', label_suffix='MPa', help_text='Máximo stress disponible', widget=forms.NumberInput(attrs={'step': '50'}), min_value=0, max_value=500) def __init__(self, *args, **kwargs): super(MechanicalInputForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False #form attributes disabled self.helper.disable_csrf = True self.helper.label_class = 'col-md-4' self.helper.field_class = 'col-md-8' #Custom atributes self.helper.label_info = True self.helper.append_label_suffix = True self.helper.layout = Layout( Div(Div(HTML("""<h3 class="title">Variables Mecanicas</h3>""")), Div( 'Bs_t', 'Bs_c', 'e', 'R', 's_max', 'Cs', 'Ci', 'Ml', ), css_class='col-md-4 col-sm-6 m-form'), ) self.helper.filter_by_widget(forms.NumberInput).wrap( AppendedText, ' ', css_class="input-sm") #bfh-number class Meta: model = MechanicalInput fields = ['Bs_t', 'Bs_c', 'e', 'R', 's_max', 'Cs', 'Ci', 'Ml'] limits = [ ['5e3', '1e3', '1e5'], #Bs_t ['5e3', '-1e5', '-1e3'], #Bs_c ['5e-16', '1e-16', '1e-14'], #e ['1e-2', '1', '10'], #R ['50', '10', '500'], #mx_s ] """
class ThermalInputForm(forms.ModelForm): """ Form for the thermal input that uses crispy_forms """ k_cs = forms.FloatField(label='k (c.s.)', label_suffix='W/mK', help_text='Conductividad térmica de la corteza \ superior', widget=forms.NumberInput(attrs={'step': '0.1'}), min_value=1, max_value=5) k_ci = forms.FloatField(label='k (c.i.)', label_suffix='W/mK', help_text='Conductividad térmica de la corteza \ inferior', widget=forms.NumberInput(attrs={'step': '0.1'}), min_value=1, max_value=5) k_ml = forms.FloatField(label='k (m.l.)', label_suffix='W/mK', help_text='Conductividad térmica del manto \ litosférico', widget=forms.NumberInput(attrs={'step': '0.1'}), min_value=1, max_value=5) H_cs = forms.FloatField(label='H (c.s.)', label_suffix='W/m³', help_text='Producción de calor radiogénico en la \ corteza superior', widget=forms.NumberInput(attrs={'step': '5e-7'}), min_value=1e-6, max_value=1e-5) H_ci = forms.FloatField(label='H (c.i.)', label_suffix='W/m³', help_text='Producción de calor radiogénico en la \ corteza inferior', widget=forms.NumberInput(attrs={'step': '5e-7'}), min_value=1e-6, max_value=1e-5) H_ml = forms.FloatField(label='H (m.l.)', label_suffix='W/m³', help_text='Producción de calor radiogénico en el \ manto litosférico', widget=forms.NumberInput(attrs={'step': '5e-7'}), min_value=1e-6, max_value=1e-5) delta = forms.FloatField(label='δ', label_suffix='km', help_text='Factor de escala para el decaimiento \ exponencial de la producción de calor \ radiogénico', widget=forms.NumberInput(attrs={'step': '1'}), min_value=1, max_value=30) Tp = forms.FloatField(label='Tm', label_suffix='ºC', help_text='Temperatura potencial del manto \ astenosférico en la superficie', widget=forms.NumberInput(attrs={'step': '100'}), min_value=500, max_value=1500) G = forms.FloatField(label='G', label_suffix='K/m', help_text='Gradiante adiabático', widget=forms.NumberInput(attrs={'step': '5e-5'}), min_value=1e-4, max_value=1e-3) kappa = forms.FloatField(label='κ', label_suffix='m²/s', help_text='Difusividad térmica', widget=forms.NumberInput(attrs={'step': '5e-7'}), min_value=1e-6, max_value=1e-5) V = forms.FloatField(label='V', label_suffix='m/Ma', help_text='Velocidad de convergencia', widget=forms.NumberInput(attrs={'step': '5e3'}), min_value=1e4, max_value=1e5) dip = forms.FloatField(label='α', label_suffix='º', help_text='Ángulo de subducción promedio', widget=forms.NumberInput(attrs={'step': '1'}), min_value=0, max_value=90) b = forms.FloatField(label='b', label_suffix='', help_text='Parametro adimensional', widget=forms.NumberInput(attrs={'step': '0.1'}), min_value=0.1, max_value=1) t = forms.FloatField(label='t', label_suffix='Ma', help_text='Edad de la corteza oceánica subductada en \ la fosa', widget=forms.NumberInput(attrs={'step': '5'}), min_value=0, max_value=100) D = forms.FloatField(label='D', label_suffix='', help_text='Parámetro que regula el decrecimiento \ exponencial del stress de cizalle a lo largo del \ limite entre placas', widget=forms.NumberInput(attrs={'step': '1'}), min_value=1, max_value=5) def __init__(self, *args, **kwargs): super(ThermalInputForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False #form attributes disabled self.helper.disable_csrf = True self.helper.label_class = 'col-md-4' self.helper.field_class = 'col-md-8' #self.form_show_errors = False #Custom attributes self.helper.label_info = True self.helper.append_label_suffix = True self.helper.help_and_error = True self.helper.layout = Layout( Div(Div(HTML("""<h3 class="title">Variables Termales</h3>""")), Div('k_z', 'H_z', 'delta_icd', 't_lat', 'k_cs', 'k_ci', 'k_ml', 'H_cs', 'H_ci', 'H_ml', css_class='col-md-6 col-sm-12'), Div('delta', 'Tp', 'G', 'kappa', 'V', 'dip', 'b', 't', 'D', css_class='col-md-6 col-sm-12'), css_class='col-md-8 col-sm-6 t-form'), ) self.helper.filter_by_widget(forms.NumberInput).wrap( AppendedText, ' this is replaced by label_suffix bc append_label_suffix=True', css_class="input-sm") class Meta: model = ThermalInput fields = [ 'k_z', 'H_z', 'delta_icd', 't_lat', 'k_cs', 'k_ci', 'k_ml', 'H_cs', 'H_ci', 'H_ml', 'delta', 'Tp', 'G', 'kappa', 'V', 'dip', 'b', 't', 'D' ] """
class InformeSemestralForm(forms.ModelForm): """Formulario para crear un comentario""" class Meta: model = InformeSemestral exclude = ['edificacion', 'fecha_elaboracion', 'informe'] 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"), ))
class BaseApplicationForm(forms.Form): """ Given a dict of parameters describing the required fields for this application, constructs a suitable application form. Expected dict format: { 'user': [list, of, required, user, data, fields], 'partner_1': [list, of, required, fields, for, partner, 1], 'partner_2': [list, of, required, fields, for, partner, 2], (additional partners as needed) } 'user' is mandatory. 'partner_1' is mandatory. Additional partners are optional. See https://django-crispy-forms.readthedocs.org/ for information on form layout. """ def __init__(self, *args, **kwargs): self._validate_parameters(**kwargs) self.field_params = kwargs.pop("field_params") try: self.user = kwargs.pop("requested_user") except KeyError: pass super(BaseApplicationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self._initialize_form_helper() self.helper.layout = Layout() user_data = self.field_params.pop("user") self._add_user_data_subform(user_data) # For each partner, build a partner data section of the form. for partner in self.field_params: self._add_partner_data_subform(partner) # Make sure to align any checkbox inputs with other field types self.helper.filter_by_widget(forms.CheckboxInput).wrap( Div, css_class= "col-sm-8 col-sm-offset-4 col-md-9 col-md-offset-3 apply-tos") self.helper.add_input( Submit( "submit", # Translators: Labels the button users click to apply for a partner's resources. _("Apply"), css_class="center-block", )) def _get_partner_object(self, partner): # Extract the number component of (e.g.) 'partner_1'. try: partner_id = partner[8:] # Verify that it is the ID number of a real partner. partner = Partner.objects.get(id=partner_id) return partner except Partner.DoesNotExist: logger.exception("BaseApplicationForm received a partner ID that " "did not match any partner in the database") raise def _validate_parameters(self, **kwargs): """ Ensure that parameters have been passed in and match the format specified in the docstring. """ try: field_params = kwargs["field_params"] except KeyError: logger.exception("Tried to instantiate a BaseApplicationForm but " "did not have field_params") raise try: assert "user" in field_params except AssertionError: logger.exception("Tried to instantiate a BaseApplicationForm but " "there was no user parameter in field_params") raise try: # We should have 'user' plus at least one partner in the keys. assert len(list(field_params.keys())) >= 2 except AssertionError: logger.exception( "Tried to instantiate a BaseApplicationForm but " "there was not enough information in field_params") raise expected = re.compile(r"partner_\d+") for key in list(field_params.keys()): # All keys which are not the user data should be partner data. if key != "user": try: assert expected.match(key) except AssertionError: logger.exception( "Tried to instantiate a BaseApplicationForm but " "there was a key that did not match any expected values" ) def _validate_user_data(self, user_data): try: assert set(user_data) <= set(USER_FORM_FIELDS) except AssertionError: logger.exception("BaseApplicationForm received invalid user data") raise def _validate_partner_data(self, partner_data): try: assert set(partner_data) <= set(PARTNER_FORM_OPTIONAL_FIELDS) except AssertionError: logger.exception( "BaseApplicationForm received invalid partner data") raise def _initialize_form_helper(self): # Add basic styling to the form. self.helper.form_class = "form-horizontal" self.helper.label_class = "col-xs-12 col-sm-4 col-md-3" self.helper.field_class = "col-xs-12 col-sm-8 col-md-9" def _add_user_data_subform(self, user_data): self._validate_user_data(user_data) if user_data: # Translators: This labels a section of a form where we ask users to enter personal information (such as their country of residence) when making an application. user_data_layout = Fieldset(_("About you")) for datum in user_data: self.fields[datum] = FIELD_TYPES[datum] self.fields[datum].label = FIELD_LABELS[datum] # Show which partner wants which personal data if applying # for more than one. if len(self.field_params) > 1: # fmt: off # Translators: This text is shown in the application form under each piece of personal information requested. {partner_list} will be a list of 2 or more organisations that require this personal data, and should not be translated. self.fields[datum].help_text = _( "Requested by: {partner_list}").format( partner_list=", ".join(user_data[datum])), # fmt: on user_data_layout.append(datum) self.helper.layout.append(user_data_layout) # fmt: off # Translators: This note appears in a section of a form where we ask users to enter info (like country of residence) when applying for resource access. disclaimer_html = _( "<p><small><i>Your personal data will be processed according to our <a href='{terms_url}'> privacy policy</a>.</i></small></p>" ).format(terms_url=reverse("terms")) # fmt: on self.helper.layout.append(HTML(disclaimer_html)) def _add_partner_data_subform(self, partner): partner_data = self.field_params[partner] partner_object = self._get_partner_object(partner) partner_layout = Fieldset( # Translators: This is the title of the application form page, where users enter information required for the application. It lets the user know which partner application they are entering data for. {partner} _("Your application to {partner}").format(partner=partner_object)) self._validate_partner_data(partner_data) # partner_data lists the optional fields required by that partner; # base fields should be in the form for all partners. all_partner_data = partner_data + PARTNER_FORM_BASE_FIELDS if all_partner_data: for datum in all_partner_data: # This will yield fields with names like 'partner_1_occupation'. # This will let us tell during form processing which fields # belong to which partners. field_name = "{partner}_{datum}".format(partner=partner, datum=datum) self.fields[field_name] = FIELD_TYPES[datum] self.fields[field_name].label = FIELD_LABELS[datum] if datum == AGREEMENT_WITH_TERMS_OF_USE: # Make sure that, if the partner requires agreement with # terms of use, that link is provided inline. help_text = '<a href="{url}">{url}</a>'.format( url=partner_object.terms_of_use) self.fields[field_name].help_text = help_text if datum == SPECIFIC_STREAM: # Only show streams for this partner partner_id = int(partner[8:]) # We use the logic below to filter out the streams for which # the user already has authorizations. Streams with authorizations # can only be renewed (as opposed to applying) from the My Library # page. queryset = Stream.objects.filter(partner_id=partner_id) # We need a user if we are to determine which streams have authorizations. # We set the user in the view code if a partner has streams. if self.user: all_authorizations = Authorization.objects.filter( user=self.user, partners=partner_id, stream__isnull=False) existing_streams = [] for each_authorization in all_authorizations: existing_streams.append( each_authorization.stream.id) if len(existing_streams) > len(set(existing_streams)): logger.info( "Multiple authorizations returned for the same partner {}, same stream for user {}. " "Unable to pop options.".format( partner_id, self.user)) break else: # We exclude the streams that already have authorizations. queryset = Stream.objects.exclude( id__in=existing_streams).filter( partner_id=partner_id) specific_stream = forms.ModelChoiceField(queryset=queryset, empty_label=None) self.fields[field_name] = specific_stream self.fields[field_name].label = FIELD_LABELS[datum] if datum == ACCOUNT_EMAIL: # If partner requires pre-registration, make sure users # get a link where they can sign up. url = '<a href="{url}">{url}</a>'.format( url=partner_object.registration_url) # Translators: For some applications, users must register at another website before finishing the application form, and must then enter their email address used when registering. Don't translate {url}. help_text = _("You must register at {url} before applying." ).format(url=url) self.fields[field_name].help_text = help_text partner_layout.append(field_name) self.helper.layout.append(partner_layout)
class InformeSemestralForm(forms.ModelForm): """Formulario para crear un comentario""" class Meta: model = InformeSemestral exclude = ['edificacion','fecha_elaboracion','informe'] 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"), ) )