Esempio n. 1
0
    def __init__(self, *args, **kwargs):
        super(ExamsForm, self).__init__(*args, **kwargs)
        data_client = DataClient()
        completed = []
        obs = data_client.observations
        for exam in data_client.physical_exam:
            for form in exam['forms']:
                if form['code'] in obs:
                    completed.append(exam['code'])
                    break
        self.helper = FormHelper()
        self.helper.layout = Layout()
        field_set = Fieldset("Please select exam(s) to complete")
        for exam in data_client.physical_exam:
            if exam['code'] in completed:
                self.fields[exam['code']] = forms.BooleanField(
                    label=exam['name'] + " (Completed)",
                    required=False,
                )
            else:
                self.fields[exam['code']] = forms.BooleanField(
                    label=exam['name'],
                    required=False,
                )

            field_set.append(Field(exam['code']))
        self.helper.layout.append(field_set)
        self.helper.add_input(Submit('submit', 'Next'))
        self.helper.form_id = 'id-examsForm'
        self.helper.form_method = 'post'
Esempio n. 2
0
 def __init__(self, *args, **kwargs):
     super(AssessmentForm, self).__init__(*args, **kwargs)
     data_client = DataClient()
     # assessments_chosen = data_client.assessments_chosen
     self.helper = FormHelper()
     self.helper.layout = Layout()
     field_set = Fieldset("Please select assessment(s) to complete")
     for test in data_client.func_test:
         if test['code'] in data_client.observations:
             self.fields[test['code']] = forms.BooleanField(
                 label=test['name'] + " (Completed)",
                 required=False,
             )
         elif test['is_recommended']:
             self.fields[test['code']] = forms.BooleanField(
                 label=test['name'] + " (Recommended)",
                 required=False,
             )
         else:
             self.fields[test['code']] = forms.BooleanField(
                 label=test['name'],
                 required=False,
             )
         field_set.append(Field(test['code']))
     self.helper.layout.append(field_set)
     self.helper.add_input(Submit('submit', 'Next'))
     self.helper.form_id = 'id-assessmentForm'
     self.helper.form_method = 'post'
Esempio n. 3
0
    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')))))
Esempio n. 4
0
    def __init__(self, *args, **kwargs):
        assessments_chosen = kwargs.pop("assessments_chosen", None)
        super(AssessmentDetailsForm, self).__init__(*args, **kwargs)
        data_client = DataClient()
        # assessments_chosen = data_client.assessments_chosen
        self.helper = FormHelper()
        self.helper.layout = Layout()
        i = 0
        if assessments_chosen:
            # self.helper.layout.append(HTML (
            #     <span id="hiddenTag" style="display: none">{{ i }}</span>
            # ))
            # self.helper.layout.append(Button (
            # ))
            for test in data_client.func_test:
                if test['code'] in assessments_chosen:

                    code = test['code']
                    test_fieldset = Fieldset(test['name'],
                                             css_class=test['name'])
                    # self.helper.layout.append(Button(test['code'], test['code']))
                    for i, form in enumerate(test['forms']):
                        code = test['forms'][i]['code']
                        field_name = code
                        self.fields[field_name] = generate_form(
                            form, None, None)
                        test_fieldset.append(Field(field_name))
                        # self.fields[field_name].widget = forms.HiddenInput()
                    self.helper.layout.append(test_fieldset)
            self.helper.add_input(Submit('submit', 'Submit'))
        self.helper.form_id = 'id-assessmentForm'
        self.helper.form_method = 'post'
Esempio n. 5
0
    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 info (like country of residence) when applying for resource access.
            user_data_layout = Fieldset(_('About you'))
            for datum in user_data:
                self.fields[datum] = FIELD_TYPES[datum]
                self.fields[datum].label = FIELD_LABELS[datum]
                user_data_layout.append(datum)

            self.helper.layout.append(user_data_layout)
Esempio n. 6
0
    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)
Esempio n. 7
0
    def _get_form_fieldset(self, items, text, **attrs):

        # Collect them
        fieldset = Fieldset(text, **attrs)

        # Get all the not groups
        for item in items:

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

                # Add those group items
                fieldset.append(self._get_form_fieldset(item.item, item.text))

            elif item.type == 'display':

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

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

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

                # Check for groups
                for subitem in item.item:

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

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

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

            else:

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

        return fieldset
Esempio n. 8
0
 def __init__(self, *args, **kwargs):
     exams_chosen = kwargs.pop("exams_chosen", None)
     super(ExamsDetailsForm, self).__init__(*args, **kwargs)
     data_client = DataClient()
     self.helper = FormHelper()
     self.helper.layout = Layout()
     if exams_chosen:
         for exam in data_client.physical_exam:
             if exam['code'] in exams_chosen:
                 exam_fieldset = Fieldset(exam['name'],
                                          css_class=exam['name'])
                 for i, form in enumerate(exam['forms']):
                     code = exam['forms'][i]['code']
                     field_name = code
                     self.fields[field_name] = generate_form(form)
                     exam_fieldset.append(Field(field_name))
                 self.helper.layout.append(exam_fieldset)
         self.helper.add_input(Submit('submit', 'Submit'))
     self.helper.form_id = 'id-examsForm'
     self.helper.form_method = 'post'
Esempio n. 9
0
    def _add_partner_data_subform(self, partner):
        partner_data = self.field_params[partner]
        partner_object = self._get_partner_object(partner)
        partner_layout = Fieldset(
            _('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]

                partner_layout.append(field_name)

            self.helper.layout.append(partner_layout)
Esempio n. 10
0
    def __init__(self, *args, **kwargs):
        risk_level = kwargs.pop("risk_level", None)
        incomplete = kwargs.pop("incomplete_list", None)
        super(RisksForm, self).__init__(*args, **kwargs)
        data_client = DataClient()
        self.helper = FormHelper()
        self.helper.layout = Layout()

        intervention_list = []
        print(risk_level)
        if risk_level == "low" or risk_level == "incomplete":
            for intervention in data_client.risk_list["risks"]["low_risk"]:
                intervention_list.append(intervention)
        elif risk_level == "moderate":
            for intervention in data_client.risk_list["risks"][
                    "moderate_risk"]:
                intervention_list.append(intervention)
        elif risk_level == "high":
            for intervention in data_client.risk_list["risks"]["high_risk"]:
                intervention_list.append(intervention)
        print(intervention_list)
        # Pythonic way to check if list isn't empty
        if intervention_list:
            for intervention in intervention_list:
                current_intervention = data_client.intervention_list[
                    intervention]
                intervention_fieldset = Fieldset(current_intervention['name'],
                                                 css_class='field_set_results')
                for i, form in enumerate(current_intervention['forms']):
                    code = current_intervention['forms'][i]['code']
                    field_name = code
                    self.fields[field_name] = generate_form(form)
                    intervention_fieldset.append(Field(field_name))
                self.helper.layout.append(intervention_fieldset)
            print("here")

        self.helper.form_id = 'id-risksForm'
        self.helper.form_method = 'post'
        self.helper.add_input(Submit('submit', 'Complete'))
Esempio n. 11
0
    def __init__(self, *args, **kwargs):
        try:
            self.field_params = kwargs.pop("field_params")
        except KeyError:
            logger.exception(
                "Tried to instantiate a RenewalForm but did not have field_params"
            )
            raise
        super(RenewalForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        # Translators: This will be the title of the page where users will have to confirm their renewal request of an application.
        fieldset = Fieldset(_("Renewal confirmation"))

        account_email = False
        if ("account_email" in self.field_params
                and self.field_params["account_email"] is not None):
            self.fields["account_email"] = forms.EmailField(
                initial=self.field_params["account_email"])
            account_email = True
        elif "account_email" in self.field_params:
            self.fields["account_email"] = forms.EmailField()
            account_email = True
        if account_email:
            # fmt: off
            # Translators: This labels an email field where users will be asked to enter their emails as part of the application renewal confirmation.
            self.fields["account_email"].label = _(
                "The email for your account on the partner's website")
            # fmt: on
            fieldset.append("account_email")

        if "requested_access_duration" in self.field_params:
            self.fields["requested_access_duration"] = forms.ChoiceField(
                choices=Application.REQUESTED_ACCESS_DURATION_CHOICES)
            # fmt: off
            # Translators: This labels a choice field where users will have to select the number of months they wish to have their access for as part of the application renewal confirmation.
            self.fields["requested_access_duration"].label = _(
                "The number of months you wish to have this access for before renewal is required"
            )
            # fmt: on
            fieldset.append("requested_access_duration")

        self.fields["return_url"] = forms.CharField(widget=forms.HiddenInput,
                                                    max_length=70)
        self.fields["return_url"].initial = self.field_params["return_url"]
        fieldset.append("return_url")

        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = "col-lg-3"
        self.helper.field_class = "col-lg-4"

        self.helper.layout = Layout()
        self.helper.layout.append(fieldset)
Esempio n. 12
0
    def __init__(self, *args, **kwargs):
        try:
            self.field_params = kwargs.pop('field_params')
        except KeyError:
            logger.exception('Tried to instantiate a RenewalForm but '
                             'did not have field_params')
            raise
        super(RenewalForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        # Translators: This will be the title of the page where users will have to confirm their renewal request of an application.
        fieldset = Fieldset(_('Renewal confirmation'))

        account_email = False
        if 'account_email' in self.field_params and self.field_params[
                'account_email'] is not None:
            self.fields['account_email'] = forms.EmailField(
                initial=self.field_params['account_email'])
            account_email = True
        elif 'account_email' in self.field_params:
            self.fields['account_email'] = forms.EmailField()
            account_email = True
        if account_email:
            # Translators: This labels an email field where users will be asked to enter their emails as part of the application renewal confirmation.
            self.fields['account_email'].label = _(
                'The email for your account on the partner\'s website')
            fieldset.append('account_email')

        if 'requested_access_duration' in self.field_params:
            self.fields['requested_access_duration'] = forms.ChoiceField(
                choices=Application.REQUESTED_ACCESS_DURATION_CHOICES, )
            # Translators: This labels a choice field where users will have to select the number of months they wish to have their access for as part of the application renewal confirmation.
            self.fields['requested_access_duration'].label = _(
                'The number of months you wish to have this access'
                ' for before renewal is required')
            fieldset.append('requested_access_duration')

        self.fields['return_url'] = forms.CharField(
            widget=forms.HiddenInput,
            max_length=70,
        )
        self.fields['return_url'].initial = self.field_params['return_url']
        fieldset.append('return_url')

        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-4'

        self.helper.layout = Layout()
        self.helper.layout.append(fieldset)
Esempio n. 13
0
        def __init__(self, *args, **kwargs):
            super(GenericEntitiesForm, self).__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.helper.form_class = entity.title() + 'Form'
            self.helper.form_tag = False
            self.helper.help_text_inline = True
            acc_grp1 = Fieldset('Metadata {}'.format(entity.title()))
            acc_grp2 = AccordionGroup('MetaInfo', 'references', 'notes',
                                      'review')
            attrs = {
                'data-placeholder': 'Type to get suggestions',
                'data-minimum-input-length': 1,
                'data-html': True
            }
            for f in self.fields.keys():
                if isinstance(self.fields[f],
                              (ModelMultipleChoiceField, ModelChoiceField)):
                    v_name_p = str(self.fields[f].queryset.model.__name__)
                    if isinstance(self.fields[f], ModelMultipleChoiceField):
                        widget1 = Select2Multiple
                    else:
                        widget1 = ListSelect2
                    if ContentType.objects.get(
                            app_label__in=[
                                'apis_entities', 'apis_metainfo',
                                'apis_relations', 'apis_vocabularies',
                                'apis_labels'
                            ],
                            model=v_name_p.lower()).app_label.lower(
                            ) == 'apis_vocabularies':
                        self.fields[f].widget = widget1(url=reverse(
                            'apis:apis_vocabularies:generic_vocabularies_autocomplete',
                            kwargs={
                                'vocab': v_name_p.lower(),
                                'direct': 'normal'
                            }),
                                                        attrs=attrs)
                        if self.instance:
                            res = []
                            if isinstance(self.fields[f],
                                          ModelMultipleChoiceField):
                                try:
                                    for x in getattr(self.instance, f).all():
                                        res.append((x.pk, x.label))
                                except ValueError:
                                    pass
                                self.fields[f].initial = res
                                self.fields[f].choices = res
                            else:
                                try:
                                    res = getattr(self.instance, f)
                                    if res is not None:
                                        self.fields[f].initial = (res.pk,
                                                                  res.label)
                                        self.fields[f].choices = [
                                            (res.pk, res.label),
                                        ]
                                except ValueError:
                                    res = ''
                if f not in acc_grp2:
                    acc_grp1.append(f)
            if entity == 'Person':
                acc_grp1 = Fieldset('Metadata {}'.format(entity.title()))
                person_field_list = [
                    'name',
                    'first_name',
                    'gender',
                    'title',
                    'profession',
                    'start_date_written',
                    'end_date_written',
                    'status',
                    'collection',
                ]
                for x in person_field_list:
                    acc_grp1.append(x)

            self.helper.layout = Layout(Accordion(acc_grp1, acc_grp2))
            self.fields['status'].required = False
            self.fields['collection'].required = False
            self.fields['start_date_written'].required = False
            self.fields['end_date_written'].required = False
Esempio n. 14
0
    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 Collection
                    # 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,
                            partner=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)
Esempio n. 15
0
    def __init__(self, *args, **kwargs):
        #global question1, question2
        print("StationDetailForm - init")
        #dir(StationDetailForm.question1)
        #StationDetailForm.question1 = forms.CharField(label = "different question",required = True,)
        #pprint(StationDetailForm.question1)
        #question2 = forms.CharField(label = "Question 2",required = True,)

        print("len(args[0])=" + str(len(args[0])))
        stationQuestions = args[0]
        pprint(stationQuestions)

        self.helper = FormHelper()
        self.helper.form_id = 'id-stationsDataForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'

        self.helper.layout = Layout()

        # first questions - the current situation
        nq = len(stationQuestions["Current-questions"])
        if (nq > 0):
            questionsFieldset = Fieldset(
                '',  # legend of the fieldset
                HTML("""<h3>Your current situation:</h3> """))

            for i in range(nq):
                questionsFieldset.append(
                    HTML("<p>" + stationQuestions["Current-questions"][i] +
                         "</p>"))
                response = stationQuestions["Current-responses"][i]
                if response['type'] == "NUMBER_BETWEEN":
                    valuerange = (response['values'][0]['userEnteredValue'],
                                  response['values'][1]['userEnteredValue'])
                    pprint(valuerange)
                    name = 'integer' + str(i)
                    questionsFieldset.append(name)
                elif response['type'] == "ONE_OF_RANGE":
                    valuesString = response['values'][0]['userEnteredValue']
                    if valuesString == "=YesNo":
                        choices = ["yes", "no"]
                    name = 'choice' + str(i)
                    questionsFieldset.append(name)
                else:
                    pprint(response['type'])
                    name = 'question' + str(i)
                    questionsFieldset.append(name)

            self.helper.layout.append(questionsFieldset)

        # next questions - the planned situation
        if (len(stationQuestions["Planned-questions"]) > 0):
            anotherFieldset = Fieldset(
                '',  # legend of the fieldset
                HTML("""<hr><h3>What you plan to do</h3>"""))
            anotherFieldset.append('question2')
            self.helper.layout.append(anotherFieldset)

        self.helper.layout.append(
            FormActions(
                Button('estimate', 'Estimate'),
                Button('submit', 'Continue'),
            ))
        #for i in range(numQuestions):
        #    txt = 'question'+str(i+1)
        #    self.helper.layout[0].append(txt)

        #self.helper.layout[0]

        self.helper.form_action = 'submit_survey'
        super(StationDetailForm, self).__init__()