Ejemplo n.º 1
0
Archivo: forms.py Proyecto: rizac/eGSIM
class TestingForm(GsimImtForm, GmdbForm):
    '''Form for testing Gsims via Measures of Fit'''

    # py3 dict merge (see https://stackoverflow.com/a/26853961/3526777):
    __additional_fieldnames__ = {**GsimImtForm.__additional_fieldnames__,
                                 **GmdbForm.__additional_fieldnames__,
                                 'fitm': 'fit_measure'}

    fit_measure = MeasureOfFitField(required=True, label="Measure(s) of fit")

    edr_bandwidth = FloatField(required=False, initial=0.01,
                               help_text=('Ignored if EDR is not a '
                                          'selected measure of fit'))
    edr_multiplier = FloatField(required=False, initial=3.0,
                                help_text=('Ignored if EDR is not a '
                                           'selected measure of fit'))

    def clean(self):
        # Note: the call below calls GmdbPlot.clean(self) BUT we should
        # check why and how:
        cleaned_data = GsimImtForm.clean(self)
        config = {}
        for parname in ['edr_bandwidth', 'edr_multiplier']:
            if parname in cleaned_data:
                config[parname] = cleaned_data[parname]
        cleaned_data['config'] = config
        return cleaned_data
Ejemplo n.º 2
0
class GsimSelectionForm(BaseForm):
    '''Form for (t)ectonic (r)egion gsim selection from a point or rectangle.
    This form is currently only used as validator as the HTML page renderes
    a custom map.
    '''

    __additional_fieldnames__ = {
        'lat': 'latitude',
        'lon': 'longitude',
        'lat2': 'latitude2',
        'lon2': 'longitude2',
        'gmpe': 'gsim'
    }

    # NOTE: DO NOT set initial
    gsim = GsimField(required=False)
    imt = ImtclassField(required=False)

    model = TrModelField(label='Tectonic region model', required=False)
    longitude = FloatField(label='Longitude',
                           min_value=-180,
                           max_value=180,
                           required=False)
    latitude = FloatField(label='Latitude',
                          min_value=-90,
                          max_value=90,
                          required=False)
    longitude2 = FloatField(label='Longitude 2nd point',
                            min_value=-180,
                            max_value=180,
                            required=False)
    latitude2 = FloatField(label='Latitude 2nd point',
                           min_value=-90,
                           max_value=90,
                           required=False)
    trt = TrtField(label='Tectonic region type(s)', required=False)

    def clean(self):
        '''Checks that if longitude is provided, also latitude is provided,
        and vice versa (the same for longitude2 and latitude2)'''
        cleaned_data = super().clean()

        # check that params combinations are ok:
        couplings = (('latitude', 'longitude'), ('longitude2', 'latitude2'))
        for (key1, key2) in couplings:
            val1, val2 = \
                cleaned_data.get(key1, None), cleaned_data.get(key2, None)
            if val1 is None and val2 is not None:
                # instead of raising ValidationError, which is keyed with
                # '__all__' we add the error keyed to the given field name
                # `name` via `self.add_error`:
                # https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
                error = ValidationError(_("missing value"), code='missing')
                self.add_error(key1, error)
            elif val1 is not None and val2 is None:
                error = ValidationError(_("missing value"), code='missing')
                self.add_error(key2, error)

        return cleaned_data
Ejemplo n.º 3
0
 def get_total(self):
     total = PurchaseItem.objects.filter(purchase=self) \
         .annotate(
         subtotal=ExpressionWrapper(
             Sum(F('price') * F('quantity')), output_field=FloatField()
         )).aggregate(total=Sum('subtotal'))
     return total['total']
Ejemplo n.º 4
0
class ResponseForm(ModelForm):
    term = ModelChoiceField(Term.objects.all(), widget=HiddenInput)
    valence = FloatField(initial="0",
                         widget=HiddenInput(attrs={"class": "valence-input"}))
    request = SlugField()

    class Meta:
        model = Response
Ejemplo n.º 5
0
class SubmissionForm(ModelForm):
    request = ModelChoiceField(Request.objects.all(),
                               widget=HiddenInput,
                               to_field_name="slug")
    term = ModelChoiceField(Term.objects.all(),
                            widget=HiddenInput,
                            to_field_name="body")
    valence = FloatField(initial="0",
                         widget=HiddenInput(attrs={"class": "valence-input"}))

    class Meta:
        model = Submission
Ejemplo n.º 6
0
class GenericForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(GenericForm, self).__init__(*args, **kwargs)
        backends = get_backend_choices()
        self.fields['backend'] = ChoiceField(
            choices=backends,
            initial=backends[0][0] if len(backends) else '',
            widget=widgets.HiddenInput,
        )

    summ = FloatField()
    order = ModelChoiceField(widget=HiddenInput,
                             required=False,
                             queryset=Order.objects.all())
Ejemplo n.º 7
0
class PaymentMethodForm(forms.Form):
    """
    Displays all available payments backends as choice list.
    """
    def __init__(self, *args, **kwargs):
        super(PaymentMethodForm, self).__init__(*args, **kwargs)
        backends = get_backend_choices()
        self.fields['backend'] = ChoiceField(
            choices=backends,
            initial=backends[0][0] if len(backends) else '',
            label=_("Payment method"),
            widget=PaymentRadioSelect,
        )

    order = ModelChoiceField(widget=HiddenInput,
                             required=False,
                             queryset=Order.objects.all())
    summ = FloatField(label=_("Amount"), initial=0, required=True)
Ejemplo n.º 8
0
 def __init__(self, *args, min_value=D(m=10), max_value=D(m=100),
              initial_unit="ft", **kwargs):
     error_messages = {
         "incomplete": "Enter a distance"
     }
     self.min_value = min_value
     self.max_value = max_value
     fields = (
         FloatField(),
         ChoiceField(choices=self.DISTANCE_UNITS,
                     initial=initial_unit)
     )
     super().__init__(
         fields=fields,
         error_messages=error_messages,
         require_all_fields=True,
         *args, **kwargs
     )
     self.widget = DistanceWidget(choices=self.DISTANCE_UNITS)
Ejemplo n.º 9
0
    def __init__(self, action, *args, **kwargs):

        # build the forms from the action attributes
        try:
            self.action_item = Action.objects.get(name=action)
        except ObjectDoesNotExist:
            self.action_item = Action(name=action, )

        attributes = self.action_item.attributes.all()

        from django.forms.models import fields_for_model
        model_fields = fields_for_model(Translation)

        model_fields = {}

        #for field in model_fields_list:
        #    print(field)
        #    model_fields[ field ] = model_fields_list[field]

        #for attr in attributes:
        #    if attr.datatype in model_fields:
        #        self.Meta.fields.append(attr.datatype)

        #if self.action_item.target_type:
        #    if not 'target' in self.Meta.fields:
        #        self.Meta.fields.append('target')

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

        # build fields from attributes
        attributes = self.action_item.attributes.all()

        for attr in attributes:

            if attr.datatype == 'target':
                qs = Item.objects.filter(id__in=list(
                    get_targets(self.instance, self.action_item.target_type)))
                att_field = TargetModelChoiceField(queryset=qs, )

            elif attr.datatype == 'query':
                qs = Item.objects.filter(id__in=list(
                    get_targets(self.instance, self.action_item.target_type)))
                att_field = TargetQueryField(queryset=qs, initial=None)

            elif attr.datatype == 'string':
                att_field = CharField(max_length=1024)

            elif attr.datatype == 'markdown':
                att_field = CharField(max_length=25600, widget=Textarea)

            elif attr.datatype == 'description':
                att_field = CharField(max_length=25600000, widget=Textarea)

            elif attr.datatype == 'boolean':
                att_field = BooleanField()

            elif attr.datatype == 'integer':
                att_field = IntegerField()

            elif attr.datatype == 'number':
                att_field = FloatField()

            elif attr.datatype == 'email':
                att_field = EmailField()

            elif attr.datatype == 'slug':
                att_field = SlugField()

            elif attr.datatype == 'url':
                att_field = URLField()

            #elif attr.datatype in model_fields:
            #    att_field = model_fields[ attr.datatype ]

            elif attr.datatype == 'image':
                att_field = MediaUploadField()

            else:
                #continue
                att_field = CharField(max_length=1024)

            att_field.initial = attr.default
            att_field.required = attr.required
            att_field.label = attr.label
            att_field.help_text = attr.help

            self.fields[attr.name] = att_field

            if attr.hidden:
                self.fields[attr.name].widget = forms.HiddenInput()

            if attr.regexp:
                validator = RegexValidator(attr.regexp,
                                           message=attr.regexp_error)
                if not att_field.validators:
                    att_field.validators = []
                att_field.validators.append(validator)

        self.set_form_control_class()
Ejemplo n.º 10
0
Archivo: forms.py Proyecto: rizac/eGSIM
class TrellisForm(GsimImtForm):
    '''Form for Trellis plot generation'''

    # py3 dict merge (see https://stackoverflow.com/a/26853961/3526777):
    __additional_fieldnames__ = {'mag': 'magnitude', 'dist': 'distance',
                                 'stddev': 'stdev',
                                 'tr': 'tectonic_region',
                                 'msr': 'magnitude_scalerel',
                                 'lineazi': 'line_azimuth',
                                 'vs30m': 'vs30_measured',
                                 'hyploc': 'hypocentre_location',
                                 'vs30measured': 'vs30_measured',
                                 **GsimImtForm.__additional_fieldnames__}

    plot_type = TrellisplottypeField(label='Plot type')
    stdev = BooleanField(label='Compute Standard Deviation(s)', required=False,
                         initial=False)

    # GSIM RUPTURE PARAMS:
    magnitude = NArrayField(label='Magnitude(s)', min_count=1)
    distance = NArrayField(label='Distance(s)', min_count=1)
    vs30 = NArrayField(label=mark_safe('V<sub>S30</sub> (m/s)'), min_value=0.,
                       min_count=1, initial=760.0)
    aspect = FloatField(label='Rupture Length / Width', min_value=0.)
    dip = FloatField(label='Dip', min_value=0., max_value=90.)
    # FIXME: removed field below, it is not used. Should we add it
    # in clean (see below)?
    #  tectonic_region = CharField(label='Tectonic Region Type',
    #                              initial='Active Shallow Crust',
    #                              widget=HiddenInput)
    rake = FloatField(label='Rake', min_value=-180., max_value=180.,
                      initial=0.)
    strike = FloatField(label='Strike', min_value=0., max_value=360.,
                        initial=0.)
    ztor = FloatField(label='Top of Rupture Depth (km)', min_value=0.,
                      initial=0.)
    magnitude_scalerel = MsrField(label='Magnitude Scaling Relation',
                                  initial="WC1994")
    initial_point = PointField(label="Location on Earth",
                               help_text='Longitude Latitude', initial="0 0",
                               min_value=[-180, -90], max_value=[180, 90])
    hypocentre_location = NArrayField(label="Location of Hypocentre",
                                      initial='0.5 0.5',
                                      help_text=('Along-strike fraction, '
                                                 'Down-dip fraction'),
                                      min_count=2, max_count=2,
                                      min_value=[0, 0], max_value=[1, 1])
    # END OF RUPTURE PARAMS
    vs30_measured = BooleanField(label=mark_safe('Is V<sub>S30</sub> '
                                                 'measured?'),
                                 help_text='Otherwise is inferred',
                                 initial=True, required=False)
    line_azimuth = FloatField(label='Azimuth of Comparison Line',
                              min_value=0., max_value=360., initial=0.)
    z1pt0 = NArrayField(label=mark_safe('Depth to 1 km/s V<sub>S</sub> '
                                        'layer (m)'),
                        min_value=0., required=False,
                        help_text=mark_safe("Calculated from the "
                                            "V<sub>S30</sub> if not given"))
    z2pt5 = NArrayField(label=mark_safe('Depth to 2.5 km/s V<sub>S</sub> '
                                        'layer (km)'),
                        min_value=0., required=False,
                        help_text=mark_safe("Calculated from the  "
                                            "V<sub>S30</sub> if not given"))
    backarc = BooleanField(label='Backarc Path', initial=False, required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # If the plot_type is spectra, remove imt and sa_period
        # and set the field as not required, so validation will be ok:
        if self.data.get('plot_type', '') in ('s', 'ss'):
            self.fields['imt'].sa_periods_str = ''  # see superclass __init__
            self.data.pop('imt', None)
            self.data.pop('sa_period', None)
            self.fields['imt'].required = False
            self.fields['sa_period'].required = False  # for safety

    def clean(self):
        cleaned_data = super(TrellisForm, self).clean()

        # calculate z1pt0 and z2pt5 if needed, raise in case of errors:
        vs30 = cleaned_data['vs30']  # surely a list with st least one element
        vs30scalar = isscalar(vs30)
        vs30s = np.array(vectorize(vs30), dtype=float)

        # check vs30-dependent values:
        for name, func in (['z1pt0', vs30_to_z1pt0_cy14],
                           ['z2pt5', vs30_to_z2pt5_cb14]):
            if name not in cleaned_data or cleaned_data[name] == []:
                values = func(vs30s)  # numpy-function
                cleaned_data[name] = \
                    float(values[0]) if vs30scalar else values.tolist()
            elif isscalar(cleaned_data[name]) != isscalar(vs30) or \
                    (not isscalar(vs30) and
                     len(vs30) != len(cleaned_data[name])):
                str_ = 'scalar' if isscalar(vs30) else \
                    '%d-elements vector' % len(vs30)
                # instead of raising ValidationError, which is keyed with
                # '__all__' we add the error keyed to the given field name
                # `name` via `self.add_error`:
                # https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
                error = ValidationError(_("value must be consistent with vs30 "
                                          "(%s)" % str_),
                                        code='invalid')
                self.add_error(name, error)

        return cleaned_data
Ejemplo n.º 11
0
    def __init__(self, path, user, *args, **kwargs):
        super(DynForm, self).__init__(*args, **kwargs)
        pathComplete = str(path)
        elements = pathComplete.split("/")
        studyName = elements[2]
        stageName = elements[3]

        for study in Study.objects.filter(studyName=str(studyName)):
            tempEntity = []

            for entity in Patient.objects.filter(
                    studyId__idStudy=study.idStudy, userOwner=user):
                tempLabel = str(entity).split(" ")
                patientLabel = tempLabel[0] + ". ID: " + tempLabel[1]
                tempEntity.append((patientLabel, patientLabel))

            choiceEnt = tuple(tempEntity)
            self.fields['Paciente'] = ChoiceField(
                tempEntity, initial=tempEntity[len(tempEntity) - 1])
            self.fields['Paciente'].widget.attrs['class'] = 'form-control'

            for stage in Stage.objects.filter(studyId=study.idStudy):
                if stage.stageType == str(stageName):
                    questionList = []
                    for questionGroups in Question_Groups.objects.filter(
                            groupStage__idStage=stage.idStage).order_by(
                                'order'):

                        for question in questionGroups.idQuestions.all():
                            questionList.append(question)

                        for question in questionList:
                            if question.questionsType == 'Char':
                                self.fields['%s' % question] = CharField(
                                    max_length=255, required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                            if question.questionsType == 'Int':
                                self.fields['%s' % question] = IntegerField(
                                    widget=forms.NumberInput(), required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                                self.fields['%s' % question].widget.attrs[
                                    'min'] = question.questionMin
                                self.fields['%s' % question].widget.attrs[
                                    'max'] = question.questionMax
                                self.fields['%s' %
                                            question].widget.attrs['step'] = 1
                            if question.questionsType == 'Real':
                                self.fields['%s' % question] = FloatField(
                                    widget=forms.NumberInput(), required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                                self.fields['%s' % question].widget.attrs[
                                    'min'] = question.questionMin
                                self.fields['%s' % question].widget.attrs[
                                    'max'] = question.questionMax
                                self.fields[
                                    '%s' % question].widget.attrs['step'] = 0.1
                            if question.questionsType == 'Date':
                                self.fields['%s' % question] = DateField(
                                    widget=forms.DateInput(), required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                            if question.questionsType == 'Time':
                                self.fields['%s' % question] = TimeField(
                                    widget=forms.TimeInput(), required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                            if question.questionsType == 'Bool':
                                self.fields[
                                    '%s' % question] = NullBooleanField(
                                        widget=forms.NullBooleanSelect(),
                                        required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' %
                                            question].widget.attrs.update({
                                                'onclick':
                                                "toggle_id_%s()" % question,
                                            })
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                            if question.questionsType == 'Img':
                                self.fields['%s' % question] = FileField(
                                    required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'
                            if question.questionsType == 'Enum':
                                choices = Choices.objects.filter(
                                    questionId__questionsId=question.
                                    questionsId)

                                list_of_choices = []
                                for choice in choices:
                                    list_of_choices.append((choice, choice))
                                tuple_of_choices = tuple(list_of_choices)
                                self.fields['%s' % question] = ChoiceField(
                                    widget=forms.Select(),
                                    choices=tuple_of_choices,
                                    required=False)
                                self.fields['%s' % question].label = str(
                                    question.questionsLabel)
                                self.fields['%s' % question].help_text = str(
                                    question.questionHelp)
                                self.fields['%s' %
                                            question].widget.attrs.update({
                                                'onchange':
                                                "toggle_id_%s()" % question,
                                            })
                                self.fields['%s' % question].widget.attrs[
                                    'class'] = 'form-control'