예제 #1
0
파일: forms.py 프로젝트: umarbrowser/nes
class SocialHistoryDataForm(ModelForm):
    smoker = TypedChoiceField(required=False,
                              empty_value=None,
                              choices=((True, _("Yes")), (False, _("No"))),
                              widget=RadioSelect(attrs={'id': 'id_smoker'}))
    ex_smoker = TypedChoiceField(required=False,
                                 empty_value=None,
                                 choices=((True, _("Yes")), (False, _("No"))),
                                 widget=RadioSelect)
    alcoholic = TypedChoiceField(
        required=False,
        empty_value=None,
        choices=((True, _("Yes")), (False, _("No"))),
        widget=RadioSelect(attrs={'id': 'id_alcoholic'}))

    class Meta:
        model = SocialHistoryData
        fields = [
            'smoker',
            'amount_cigarettes',
            'ex_smoker',
            'alcoholic',
            'alcohol_frequency',
            'alcohol_period',
            'drugs',
        ]

        widgets = dict(
            amount_cigarettes=Select(attrs={'class': 'form-control'}),
            alcohol_frequency=Select(attrs={'class': 'form-control'}),
            alcohol_period=Select(attrs={'class': 'form-control'}),
            drugs=RadioSelect(choices=(('ja_fez', _("Have already used")),
                                       ('faz', _('It is using')),
                                       ('nunca_fez', _('Have never used')))))
예제 #2
0
 def test_typedchoicefield_6(self):
     f = TypedChoiceField(
         choices=[(1, "+1"), (-1, "-1")],
         coerce=int,
         required=False,
         empty_value=None,
     )
     self.assertIsNone(f.clean(""))
예제 #3
0
    def __init__(self, *args, **kwargs):
        """Custom model form constructor to account for custom related objects,
        i.e. instances of (subclasses of) `ViewFilterField`. """
        super(ViewForm, self).__init__(*args, **kwargs)

        # Initialize form field for related `ReportType` object
        self.fields["report_type"] = ChoiceField(label="Report Type",
                                                 choices=choices.REPORT_TYPE,
                                                 required=True)

        # Initialize form fields for related `DateRange` object, assigning
        # custom date picker widgets
        self.fields["dr_type"] = TypedChoiceField(
            label="Report Date Range",
            choices=choices.DATE_RANGE_TYPE,
            coerce=int,
            widget=RadioSelect())
        self.fields["quantity"] = IntegerField(label="",
                                               min_value=1,
                                               required=False)
        self.fields["unit"] = TypedChoiceField(label="",
                                               coerce=int,
                                               choices=choices.TIME_UNIT,
                                               required=False)
        self.fields["begin"] = DateTimeField(label="",
                                             required=False,
                                             widget=DatePickerWidget())
        self.fields["end"] = DateTimeField(label="",
                                           required=False,
                                           widget=DatePickerWidget())

        # Set default form value for `DateRange`'s date range type field
        self.fields["dr_type"].initial = choices.DATE_RANGE_TYPE_FIXED

        # Fill form with existing `ViewFilterField` data if any. Unbound forms,
        # i.e. forms without data, don't have an instance id.
        if self.instance.id:
            # Note, there can at most be one `DateRange` and one `ReportType`
            # object on a view. See `models.ViewFilterField`'s docstring for
            # more info.
            for date_range in DateRange.objects.filter(
                    foreign_key=self.instance.id):
                self.fields["dr_type"].initial = date_range.dr_type

                self.fields["unit"].initial = date_range.unit
                self.fields["quantity"].initial = date_range.quantity

                if date_range.begin:
                    self.fields["begin"].initial = date_range.begin.strftime(
                        "%Y-%m-%d")
                if date_range.end:
                    self.fields["end"].initial = date_range.end.strftime(
                        "%Y-%m-%d")

            for report_type in ReportType.objects.filter(
                    foreign_key=self.instance.id):
                self.fields["report_type"].initial = report_type.value
예제 #4
0
 def test_typedchoicefield_4(self):
     # Even more weirdness: if you have a valid choice but your coercion function
     # can't coerce, you'll still get a validation error. Don't do this!
     f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
     msg = "'Select a valid choice. B is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('B')
     # Required fields require values
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean('')
예제 #5
0
    def test_typedchoicefield_has_changed(self):
        # has_changed should not trigger required validation
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True)
        self.assertFalse(f.has_changed(None, ''))
        self.assertFalse(f.has_changed(1, '1'))
        self.assertFalse(f.has_changed('1', '1'))

        f = TypedChoiceField(
            choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=str,
            required=False, initial=None, empty_value=None,
        )
        self.assertFalse(f.has_changed(None, ''))
        self.assertTrue(f.has_changed('', 'a'))
        self.assertFalse(f.has_changed('a', 'a'))
예제 #6
0
파일: forms.py 프로젝트: Jkrzy/crt-portal
    def __init__(self, *args, **kwargs):
        LocationForm.__init__(self, *args, **kwargs)

        self.question_groups = [
            QuestionGroup(
                self, ('public_or_private_school', ),
                group_name=
                _('Did this happen at a public or a private school, educational program or activity?'
                  ),
                help_text=
                _('Includes schools, educational programs, or educational activities, like training programs, sports teams, clubs, or other school-sponsored activities'
                  ),
                optional=False,
                ally_id='education-location-help-text'),
        ] + self.question_groups

        self.fields['public_or_private_school'] = TypedChoiceField(
            choices=PUBLIC_OR_PRIVATE_SCHOOL_CHOICES,
            widget=UsaRadioSelect(
                attrs={'aria-describedby': 'education-location-help-text'}),
            label='',
            required=True,
            error_messages={
                'required':
                _('Please select the type of school or educational program.')
            })
예제 #7
0
파일: forms.py 프로젝트: Jkrzy/crt-portal
    def __init__(self, *args, **kwargs):
        LocationForm.__init__(self, *args, **kwargs)
        self.question_groups = [
            QuestionGroup(
                self, ('election_details', ),
                group_name=
                _('What kind of election or voting activity was this related to?'
                  ),
                optional=False)
        ] + self.question_groups

        self.fields['election_details'] = TypedChoiceField(
            choices=ELECTION_CHOICES,
            empty_value=None,
            widget=UsaRadioSelect(
                attrs={
                    'help_text': {
                        'federal':
                        _('Presidential or congressional'),
                        'state_local':
                        _('Governor, state legislation, city position (mayor, council, local board)'
                          ),
                        'both':
                        _('Federal & State/local')
                    }
                }),
            required=True,
            error_messages={
                'required':
                _('Please select the type of election or voting activity.')
            },
            label='')
예제 #8
0
class CartAddProductForm(Form):
    quantity = TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICE,
                                coerce=int,
                                label=_("Quantity"))
    update = BooleanField(required=False,
                          initial=False,
                          widget=HiddenInput)
예제 #9
0
class SellingOnlineOverseasBusinessDetails(forms.Form):
    TURNOVER_OPTIONS = (
        ('Under 100k', 'Under £100,000'),
        ('100k-500k', '£100,000 to £500,000'),
        ('500k-2m', '£500,001 and £2million'),
        ('2m+', 'More than £2million'),
    )

    turnover = fields.ChoiceField(
        label='Turnover last year',
        help_text=(
            'You may use 12 months rolling or last year\'s annual turnover.'),
        choices=TURNOVER_OPTIONS,
        widget=widgets.RadioSelect(),
    )
    sku_count = IntegerField(
        label='How many stock keeping units (SKUs) do you have?',
        help_text=(
            'A stock keeping unit is an individual item, such as a product '
            'or a service that is offered for sale.'))
    trademarked = TypedChoiceField(
        label='Are your products trademarked in your target countries?',
        help_text=(
            'Some marketplaces will only sell products that are trademarked.'),
        label_suffix='',
        coerce=lambda x: x == 'True',
        choices=[(True, 'Yes'), (False, 'No')],
        widget=widgets.RadioSelect(),
        required=False,
    )
class CostumeBidDraftForm(ModelForm):
    required_css_class = 'required'
    error_css_class = 'error'

    active_use = TypedChoiceField(widget=RadioSelect,
                                  choices=boolean_options,
                                  label=costume_proposal_labels['active_use'],
                                  required=False)
    debut_date = CharField(label=costume_proposal_labels['debut_date'],
                           help_text=costume_proposal_help_texts['debut_date'],
                           widget=TextInput(attrs={'placeholder': 'MM/YYYY'}),
                           required=False)

    class Meta:
        model = Costume
        fields = [
            'b_title', 'performer', 'creator', 'act_title', 'debut_date',
            'active_use'
        ]
        help_texts = costume_proposal_help_texts
        labels = costume_proposal_labels
        widgets = {
            'performer':
            AddAnotherEditSelectedWidgetWrapper(
                autocomplete.ModelSelect2(url='limited-persona-autocomplete'),
                reverse_lazy('persona-add', urlconf='gbe.urls', args=[0]),
                reverse_lazy('persona-update',
                             urlconf='gbe.urls',
                             args=['__fk__', 0])),
        }
예제 #11
0
    def __init__(self, *args, **kwargs):
        super(PendingUserForm, self).__init__(*args, **kwargs)
        self.empty_permitted = False

        if "language" in self.fields:
            self.fields["language"].widget = RadioSelect(
                choices=PendingUser.LANGUAGE_CHOICES)
        if "membership_type" in self.fields:
            self.fields["membership_type"].widget = RadioSelect(
                choices=PendingUser.MEMBERSHIP_TYPE_CHOICES)
        if "is_ayy_member" in self.fields:
            self.fields["is_ayy_member"].widget = RadioSelect(
                choices=PendingUser.AYY_MEMBER_CHOICES)
        if "start_year" in self.fields:
            self.fields["start_year"] = TypedChoiceField(
                label=_(self.fields["start_year"].label),
                coerce=int,
                choices=year_choices,
                initial=timezone.now().year,
            )
        for visible in self.visible_fields():
            if visible.name not in [
                    "language",
                    "membership_type",
                    "is_ayy_member",
                    "has_accepted_policies",
            ]:
                visible.field.widget.attrs["class"] = "form-control"
예제 #12
0
    def __init__(self, user, related_document=None, *args, **kwargs):
        super().__init__(user=user, *args, **kwargs)
        self.related_document = related_document
        fields = self.fields

        if self.instance.related_item:
            del fields['on_the_fly_item']

        currency_str = related_document.currency.local_symbol
        discount_units = [
            (constants.DISCOUNT_PERCENT, '%'),
            (constants.DISCOUNT_LINE_AMOUNT,
             gettext('{currency} per line').format(currency=currency_str)),
            (constants.DISCOUNT_ITEM_AMOUNT,
             gettext('{currency} per unit').format(currency=currency_str)),
        ]

        line = self.instance
        fields['discount_unit'] = discount_unit_f = TypedChoiceField(
            choices=discount_units, coerce=int)
        discount_unit_f.initial = constants.DISCOUNT_PERCENT if line.discount_unit == constants.DISCOUNT_PERCENT else \
                                  (constants.DISCOUNT_LINE_AMOUNT if line.total_discount else constants.DISCOUNT_ITEM_AMOUNT) #HACK: see below
        discount_unit_f.widget.attrs = {'class': 'bound'}

        fields['vat_value'].initial = Vat.get_default_vat()
예제 #13
0
파일: forms.py 프로젝트: umarbrowser/nes
class BlockForm(ModelForm):
    type = TypedChoiceField(
        required=True,
        empty_value=None,
        choices=(('sequence', _('Sequence')), ('parallel_block',
                                               _('Parallel'))),
        widget=RadioSelect(
            attrs={
                'id': 'id_type',
                'required': "",
                'data-error': _('Organization type must be filled in.')
            }))

    class Meta:
        model = Block
        fields = ['number_of_mandatory_components', 'type']

        widgets = {
            'number_of_mandatory_components':
            TextInput(
                attrs={
                    'class': 'form-control',
                    'required': "",
                    'data-error': _('Quantity must be filled.')
                }),
        }
예제 #14
0
class CostumeBidDraftForm(ModelForm):
    required_css_class = 'required'
    error_css_class = 'error'

    active_use = TypedChoiceField(
        widget=RadioSelect,
        choices=boolean_options,
        label=costume_proposal_labels['active_use'],
        required=False)
    debut_date = CharField(
        label=costume_proposal_labels['debut_date'],
        help_text=costume_proposal_help_texts['debut_date'],
        widget=TextInput(attrs={'placeholder': 'MM/YYYY'}),
        required=False)

    class Meta:
        model = Costume
        fields = ['b_title',
                  'performer',
                  'creator',
                  'act_title',
                  'debut_date',
                  'active_use']
        help_texts = costume_proposal_help_texts
        labels = costume_proposal_labels
예제 #15
0
class SearchForm(Form):
    identifier_types = [(i.id, i.name)
                        for i in IdentifierType.objects.all()]
    identifier_types.insert(0, (0, 'Name'))
    search_property = TypedChoiceField(
        choices=identifier_types,
        coerce=int,
        empty_value=0
    )
    search_keyword = CharField()

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Div(
                Div(
                    Field('search_property', css_class='form-helper'),
                    css_class='col-sm-6'
                ),
                Div(
                    Field('search_keyword', css_class='form-helper'),
                    css_class='col-sm-6'
                ),
                css_class='row'
            )
        )

        super(SearchForm, self).__init__(*args, **kwargs)
예제 #16
0
파일: forms.py 프로젝트: leofn/nes
class SocialDemographicDataForm(ModelForm):
    benefit_government = TypedChoiceField(required=False,
                                          empty_value=None,
                                          choices=((True, _("Yes")), (False, _("No"))),
                                          widget=RadioSelect)

    class Meta:
        model = SocialDemographicData
        fields = ['natural_of', 'citizenship', 'profession', 'occupation', 'tv', 'dvd', 'radio', 'bath',
                  'automobile', 'wash_machine', 'refrigerator', 'freezer', 'house_maid',
                  'religion', 'payment', 'flesh_tone', 'patient_schooling', 'schooling', 'benefit_government',
                  'social_class']
        widgets = {
            'natural_of': TextInput(attrs={'class': 'form-control'}),
            'citizenship': SelectBoxCountries(attrs={'data-flags': 'true'}),
            'patient_schooling': Select(attrs={'class': 'form-control'}),
            'schooling': Select(attrs={'class': 'form-control'}),
            'flesh_tone': Select(attrs={'class': 'form-control'}),
            'religion': Select(attrs={'class': 'form-control'}),
            'profession': TextInput(attrs={'class': 'form-control', 'placeholder': _('Type in profession')}),
            'occupation': TextInput(attrs={'class': 'form-control', 'placeholder': _('Inform occupation')}),
            'payment': Select(attrs={'class': 'form-control'}),
            'tv': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'dvd': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'radio': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'bath': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'automobile': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'house_maid': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'wash_machine': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'refrigerator': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'freezer': RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, _('4 or +')))),
            'social_class': TextInput(attrs={'class': 'form-control', 'readonly': ""})
        }
예제 #17
0
 def __init__(self, *args, **kwargs):
     super(CreateForm, self).__init__(*args, **kwargs)
     # removes blank choices from Radio Select options
     self.fields['payment_method'] = TypedChoiceField(
         widget=RadioSelect(),
         choices=Request.PAYMENT_TYPES,
         label=_("Paid by:"),
         help_text=
         _("Cash/Check should only be accepted during camps and conferences, and also fill in the amount received. Use the Charge Amount box to charge to the student's account, or mark that the student was charged on the RCR if they are checking out."
           ))
예제 #18
0
    def test_typedchoicefield_has_changed(self):
        # has_changed should not trigger required validation
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")],
                             coerce=int,
                             required=True)
        self.assertFalse(f.has_changed(None, ""))
        self.assertFalse(f.has_changed(1, "1"))
        self.assertFalse(f.has_changed("1", "1"))

        f = TypedChoiceField(
            choices=[("", "---------"), ("a", "a"), ("b", "b")],
            coerce=str,
            required=False,
            initial=None,
            empty_value=None,
        )
        self.assertFalse(f.has_changed(None, ""))
        self.assertTrue(f.has_changed("", "a"))
        self.assertFalse(f.has_changed("a", "a"))
예제 #19
0
class SiteVariableForm(ModelForm):
    # TODO:
    # Fix this. This is nasty. This goes along with how site variables are
    # created and destroyed on the settings_form.html page.
    delete = TypedChoiceField(coerce=bool,
                              choices=((True, 'Yes'), ('', 'No')),
                              required=False)

    class Meta:
        model = SiteVariable
        exclude = ('site', )
예제 #20
0
    def __init__(self, *args, **kwargs):
        LocationForm.__init__(self, *args, **kwargs)
        self.question_groups = [
            QuestionGroup(
                self,
                ('public_or_private_employer',),
                group_name=WORKPLACE_QUESTIONS['public_or_private_employer'],
                optional=False
            ),
            QuestionGroup(
                self,
                ('employer_size',),
                group_name=WORKPLACE_QUESTIONS['employer_size'],
                optional=False
            )
        ] + self.question_groups

        self.fields['public_or_private_employer'] = TypedChoiceField(
            choices=PUBLIC_OR_PRIVATE_EMPLOYER_CHOICES,
            widget=UsaRadioSelect(attrs={
                'help_text': {
                    'public_employer': _('Funded by the government like a post office, fire department, courthouse, DMV, or public school. This could be at the local, state, or federal level'),
                    'private_employer': _('Businesses or non-profits not funded by the government such as retail stores, banks, or restaurants')
                }
            }),
            required=True,
            error_messages={
                'required': _('Please select what type of employer this is.')
            },
            label=''
        )

        self.fields['employer_size'] = TypedChoiceField(
            choices=EMPLOYER_SIZE_CHOICES,
            widget=UsaRadioSelect,
            required=True,
            error_messages={
                'required': _('Please select how large the employer is.')
            },
            label=''
        )
예제 #21
0
파일: forms.py 프로젝트: UchMok/crt-portal
class Details(ModelForm):
    how_many = TypedChoiceField(choices=HOW_MANY_CHOICES,
                                empty_value=None,
                                widget=UsaRadioSelect,
                                required=False)

    class Meta:
        model = Report
        fields = ['violation_summary', 'when', 'how_many']
        widgets = {
            'when': UsaRadioSelect,
        }
예제 #22
0
파일: forms.py 프로젝트: Jkrzy/crt-portal
    def __init__(self, *args, **kwargs):
        LocationForm.__init__(self, *args, **kwargs)

        self.name = 'PoliceLocation'

        self.fields['inside_correctional_facility'] = TypedChoiceField(
            choices=CORRECTIONAL_FACILITY_LOCATION_CHOICES,
            widget=UsaRadioSelect,
            required=True,
            error_messages={'required': POLICE_LOCATION_ERRORS['facility']},
            label='')

        self.fields['correctional_facility_type'] = TypedChoiceField(
            choices=CORRECTIONAL_FACILITY_LOCATION_TYPE_CHOICES,
            widget=UsaRadioSelect,
            required=False,
            label='')
        self.fields['correctional_facility_type'].widget.attrs[
            'class'] = 'margin-bottom-0 padding-bottom-0 padding-left-1'
        self.fields[
            'correctional_facility_type'].help_text = 'What type of prison or correctional facility?'
예제 #23
0
    def test_typedchoicefield_has_changed(self):
        # has_changed should not trigger required validation
        f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True)
        self.assertFalse(f.has_changed(None, ''))
        self.assertFalse(f.has_changed(1, '1'))
        self.assertFalse(f.has_changed('1', '1'))

        f = TypedChoiceField(
            choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=str,
            required=False, initial=None, empty_value=None,
        )
        self.assertFalse(f.has_changed(None, ''))
        self.assertTrue(f.has_changed('', 'a'))
        self.assertFalse(f.has_changed('a', 'a'))
예제 #24
0
class predForm(Form):
	age = IntegerField(label="What is your age?", max_value = 100, min_value = 1, required=False)
	sex = TypedChoiceField(label="What is your sex?", coerce = int, choices=SEX_CHOICES, required=False, empty_value = None)
	cp = TypedChoiceField(label="What is your chest pain type?", coerce = int, choices=CP_CHOICES, required=False, empty_value = None)
	trestbps = IntegerField(label="What is your resting blood pressure in mm Hg?", required=False)
	chol = IntegerField(label="What is your serum cholestoral in mg/dl?", required=False)
	fbs = TypedChoiceField(label="Is your fasting blood sugar > 120 mg/dl?", coerce = int, choices=FBS_CHOICES, required=False, empty_value = None)
	restecg = TypedChoiceField(label="How is your resting ecg?", coerce = int, choices=RESTECG_CHOICES, required=False, empty_value = None)
	thalach = IntegerField(label="What is your maximum heart rate achieved during excercise?", required=False)
	exang = TypedChoiceField(label="Do you have exercise induced angina?", coerce = int, choices=EXANG_CHOICES, required=False, empty_value = None)
	oldpeak = FloatField(label="What is your ST depression induced by exercise relative to rest?", required=False)
	slope = TypedChoiceField(label="What is the slope of your peak excercise ST segment?", coerce = int, choices=SLOPE_CHOICES, required=False, empty_value = None)
	ca = TypedChoiceField(label="What is the number of your major blood vessels colored during flourosopy?", coerce = int, choices=CA_CHOICES, required=False, empty_value = None)
	thal = TypedChoiceField(label="What are your thal results?", coerce = int, choices=THAL_CHOICES, required=False, empty_value = None)
예제 #25
0
class GOnetSubmitForm(ModelForm):
    qvalue = TypedChoiceField(widget=select_widget,
                              required=False,
                              choices=GOnetSubmission.qval_choices,
                              coerce=float,
                              empty_value=0)
    organism = ChoiceField(widget=RadioSelect,
                           required=True,
                           choices=GOnetSubmission.organism_choices,
                           initial='human')
    namespace = ChoiceField(widget=select_widget,
                            required=False,
                            choices=GOnetSubmission.namespace_choices,
                            initial='biological_process')
    analysis_type = ChoiceField(widget=RadioSelect,
                                required=True,
                                choices=GOnetSubmission.analysis_choices,
                                initial='enrich')
    custom_terms = CharField(widget=Textarea(attrs={'cols': 16}),
                             required=False)

    bg_type = TypedChoiceField(widget=select_widget,
                               required=False,
                               choices=GOnetSubmission.bgtype_choices,
                               empty_value='all')
    bg_cell = TypedChoiceField(widget=select_widget,
                               required=False,
                               choices=GOnetSubmission.bg_choices)
    slim = TypedChoiceField(widget=select_widget,
                            required=False,
                            choices=GOnetSubmission.slim_choices,
                            initial='goslim_generic')

    class Meta:
        model = GOnetSubmission
        fields = [
            'job_name', 'uploaded_file', 'paste_data', 'output_type', 'slim',
            'csv_separator', 'bg_file'
        ]
예제 #26
0
class QuestionForm(Form):
    def __init__(self, case, user, data=None, *args, **kwargs):
        questions = Question.objects.filter(Case=case)
        if not data:
            caseinstance = None if user is None else CaseInstance.objects.filter(Case=case, User=user).first()
            if caseinstance:
                data = {}
                answers = Answer.objects.filter(CaseInstance=caseinstance).select_related('Question')
                for answer in answers:
                    if answer.Question.Type in (Question.NUMERIC, Question.MULTIPLECHOICE):
                        data[answer.Question.fieldid()] = answer.AnswerNumeric
                    elif answer.Question.Type == Question.LINE:
                        if hasattr(answer, 'answerannotation'):
                            annotation = loads(answer.answerannotation.AnnotationJSON)
                            data[answer.Question.fieldid()] = dumps({'length': answer.answerannotation.Length,
                                                                     'length_unit': answer.answerannotation.LengthUnit,
                                                                     'slideid': answer.answerannotation.Slide_id,
                                                                     'annotation': annotation})
                            data[answer.Question.fieldid() + '-length'] = \
                                "{0:.3g} {1}".format(answer.answerannotation.Length,
                                                     answer.answerannotation.LengthUnit)
                    else:
                        data[answer.Question.fieldid()] = answer.AnswerText

        super(QuestionForm, self).__init__(data, *args, **kwargs)
        for question in questions:
            if question.Type == Question.NUMERIC:
                field = IntegerField(label=question.Text)
            elif question.Type == Question.MULTIPLECHOICE: 
                field = TypedChoiceField(
                    label=question.Text,
                    choices=QuestionItem.objects.filter(Question=question.id).values_list('Order', 'Text'),
                    coerce=int, widget=RadioSelect(attrs={'class': 'form-button-radio'}))
            elif question.Type == Question.DATE: 
                field = DateField(label=question.Text)
            elif question.Type == Question.REMARK:
                field = CharField(label=question.Text, widget=HiddenInput)
                # Add a list of bookmarks {pk, Text} to the value attribute of a hidden input
                field.widget.attrs.update({'question': question.pk, 'bookmarks': question.bookmarks()})
            elif question.Type == Question.LINE:
                field = LineField(label=question.Text)
                if data and question.fieldid() in data:
                    if question.fieldid() + '-length' in data:
                        field.widget.attrs.update({'line_length': data[question.fieldid() + '-length']})
                    field.initial = data[question.fieldid()]
            else:  # Use Question.OPENTEXT as fallthrough/default
                field = CharField(label=question.Text, widget=Textarea)

            field.required = question.Required

            self.fields[question.fieldid()] = field
예제 #27
0
파일: forms.py 프로젝트: umarbrowser/nes
class ComponentConfigurationForm(ModelForm):
    # This is needed because it will be included only when the parent is a sequence.
    random_position = TypedChoiceField(
        required=False,
        empty_value=None,
        choices=((False, _('Fixed')), (True, _('Random'))),
        widget=RadioSelect(attrs={'id': 'id_random_position'}))

    # TODO Replace "--------" by "Escolha unidade". The old code does not work because ModelChoiceField requires a
    # queryset.
    # This is needed because we want an empty_label different from "--------".
    # interval_between_repetitions_unit = ModelChoiceField(
    #     required=False,
    #     empty_label="Escolha unidade",
    #     widget=Select(attrs={'class': 'form-control', 'required': "",
    #                          'data-error': "Unidade do intervalo deve ser preenchida"}))

    class Meta:
        model = ComponentConfiguration
        fields = [
            'name', 'random_position', 'number_of_repetitions',
            'interval_between_repetitions_value',
            'interval_between_repetitions_unit'
        ]

        widgets = {
            'name':
            TextInput(attrs={'class': 'form-control'}),
            'number_of_repetitions':
            TextInput(
                attrs={
                    'class': 'form-control',
                    'required': "",
                    'data-error': _('Quantity of repetitions must be filled.')
                }),
            'interval_between_repetitions_value':
            TextInput(
                attrs={
                    'class': 'form-control',
                    'required': "",
                    'data-error': _('Interval must be filled.'),
                    'placeholder': _('Time')
                }),
            'interval_between_repetitions_unit':
            Select(
                attrs={
                    'class': 'form-control',
                    'required': "",
                    'data-error': _('Interval unit must be filled.')
                }),
        }
예제 #28
0
class OrderCreateForm(ModelForm):
    shipping_state = TypedChoiceField(choices=STATE_CHOICES)

    class Meta:
        model = Order
        fields = [
            'shipping_first_name',
            'shipping_last_name',
            'shipping_type',
            'shipping_country',
            'shipping_state',
            'shipping_postcode',
            'shipping_city',
            'shipping_to_home',
            'shipping_street',
            'shipping_home',
            'shipping_phone',
            'shipping_email',
            'pay_type',
        ]
        labels = {
            'shipping_first_name': _('Name'),
            'shipping_last_name': _('Surname'),
            'shipping_type': _('Delivery'),
            'shipping_city': _('City'),
            'shipping_country': _('Country'),
            'shipping_state': _('State'),
            'shipping_postcode': _('Post code'),
            'shipping_to_home': _('Home delivery'),
            'shipping_street': _('Street'),
            'shipping_home': _('Home number, flat number'),
            'shipping_phone': _('Phone'),
            'shipping_email': _('Email'),
            'pay_type': _('How do you plan to pay?'),
        }
        error_messages = {
            'shipping_first_name': {
                'max_length':
                _("This name is too long. Max number of letters is 100")
            },
            'shipping_last_name': {
                'max_length':
                _("This surname is too long. Max number of letters is 100")
            }
        }
        widgets = {
            # 'shipping_state': TypedChoiceField(choices=STATE_CHOICES),
            'shipping_type': RadioSelect,
            'pay_type': RadioSelect,
        }
예제 #29
0
파일: forms.py 프로젝트: UchMok/crt-portal
class Who(ModelForm):
    respondent_type = TypedChoiceField(choices=RESPONDENT_TYPE_CHOICES,
                                       empty_value=None,
                                       widget=UsaRadioSelect,
                                       required=False)

    class Meta:
        model = Report
        fields = [
            'respondent_contact_ask', 'respondent_type', 'respondent_name',
            'respondent_city', 'respondent_state'
        ]
        widgets = {
            'respondent_contact_ask': CheckboxInput,
        }
예제 #30
0
파일: forms.py 프로젝트: UchMok/crt-portal
class Where(ModelForm):
    public_or_private_employer = TypedChoiceField(
        choices=PUBLIC_OR_PRIVATE_EMPLOYER_CHOICES,
        empty_value=None,
        widget=UsaRadioSelect,
        required=False)
    public_or_private_facility = TypedChoiceField(
        choices=PUBLIC_OR_PRIVATE_FACILITY_CHOICES,
        empty_value=None,
        widget=UsaRadioSelect,
        required=False)
    public_or_private_healthcare = TypedChoiceField(
        choices=PUBLIC_OR_PRIVATE_HEALTHCARE_CHOICES,
        empty_value=None,
        widget=UsaRadioSelect,
        required=False)
    employer_size = TypedChoiceField(choices=EMPLOYER_SIZE_CHOICES,
                                     empty_value=None,
                                     widget=UsaRadioSelect,
                                     required=False)
    public_or_private_school = TypedChoiceField(
        choices=PUBLIC_OR_PRIVATE_SCHOOL_CHOICES,
        empty_value=None,
        widget=UsaRadioSelect,
        required=False)

    class Meta:
        model = Report
        fields = [
            'place', 'public_or_private_employer', 'employer_size',
            'public_or_private_school', 'public_or_private_facility',
            'public_or_private_healthcare'
        ]
        widgets = {
            'place': UsaRadioSelect,
        }
예제 #31
0
 def test_typedchoicefield_4(self):
     # Even more weirdness: if you have a valid choice but your coercion function
     # can't coerce, you'll still get a validation error. Don't do this!
     f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
     msg = "'Select a valid choice. B is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('B')
     # Required fields require values
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean('')
예제 #32
0
    def __init__(self, user, related_document=None, *args, **kwargs):
        # super(LineEditForm, self).__init__(user=user, *args, **kwargs)
        super().__init__(user=user, *args, **kwargs)
        self.related_document = related_document
        fields = self.fields

        if self.instance.related_item:
            del fields['on_the_fly_item']
        else:
            fields['on_the_fly_item'].widget = TextInput(attrs={
                'class': 'line-on_the_fly',
                'validator': 'Value'
            })

        fields['unit_price'].widget = TextInput(attrs={
            'class': 'line-unit_price bound',
            'validator': 'Decimal'
        })
        fields['quantity'].widget = TextInput(attrs={
            'class': 'line-quantity bound',
            'validator': 'PositiveDecimal'
        })
        fields['unit'].widget = TextInput(attrs={'class': 'line-unit'})
        fields['discount'].widget = TextInput(
            attrs={'class': 'line-quantity_discount bound'})

        currency_str = related_document.currency.local_symbol
        discount_units = [
            (constants.DISCOUNT_PERCENT, '%'),
            (constants.DISCOUNT_LINE_AMOUNT,
             _('{currency} per line').format(currency=currency_str)),
            (constants.DISCOUNT_ITEM_AMOUNT,
             _('{currency} per unit').format(currency=currency_str)),
        ]

        line = self.instance
        fields['discount_unit'] = discount_unit_f = TypedChoiceField(
            choices=discount_units, coerce=int)
        discount_unit_f.initial = constants.DISCOUNT_PERCENT if line.discount_unit == constants.DISCOUNT_PERCENT else \
                                  (constants.DISCOUNT_LINE_AMOUNT if line.total_discount else constants.DISCOUNT_ITEM_AMOUNT) #HACK: see below
        discount_unit_f.required = True
        discount_unit_f.widget.attrs = {'class': 'bound'}

        fields['comment'].widget = Textarea(attrs={
            'class': 'line-comment',
            'rows': 2
        })
        fields['vat_value'].initial = Vat.get_default_vat()
예제 #33
0
    def test_typedchoicefield_special_coerce(self):
        """
        A coerce function which results in a value not present in choices
        should raise an appropriate error (#21397).
        """
        def coerce_func(val):
            return decimal.Decimal('1.%s' % val)

        f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True)
        self.assertEqual(decimal.Decimal('1.2'), f.clean('2'))
        with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
            f.clean('')
        msg = "'Select a valid choice. 3 is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean('3')
예제 #34
0
 def test_typedchoicefield_2(self):
     # Different coercion, same validation.
     f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
     self.assertEqual(1.0, f.clean('1'))
예제 #35
0
 def test_typedchoicefield_3(self):
     # This can also cause weirdness: be careful (bool(-1) == True, remember)
     f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
     self.assertTrue(f.clean('-1'))
예제 #36
0
 def test_typedchoicefield_5(self):
     # Non-required fields aren't required
     f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
     self.assertEqual('', f.clean(''))
예제 #37
0
 def test_typedchoicefield_6(self):
     f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None)
     self.assertIsNone(f.clean(''))
예제 #38
0
 def test_typedchoicefield_1(self):
     f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
     self.assertEqual(1, f.clean('1'))
     msg = "'Select a valid choice. 2 is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('2')