class InputForm(Form): producao = IntegerField( label='Produção anual (t/ano)', initial=2000000, widget=TextInput) densidade = FloatField( label='Densidade da rocha (t/m³)', initial=2.6, widget=TextInput) frequencia = IntegerField( label='Frequência por semana', initial=1, widget=TextInput) turno = IntegerField( label='Turnos (horas)', initial=8, widget=TextInput) rcu = IntegerField( label='RCU (MPa)', initial=80, widget=TextInput) inclinacao = IntegerField( label='Inclinação (β)', initial=15, widget=TextInput) p1 = FloatField( label='Explosivo da coluna (g/cm³)', initial=0.8, widget=TextInput) p2 = FloatField( label='Explosivo da fundo (g/cm³)', initial=1.1, widget=TextInput)
class BM25Form(forms.Form): name = "BM25" query = CharField(required=True) target_index = CharField(required=True) reranker = CharField(required=True) b = FloatField(required=False) k1 = FloatField(required=False)
class LieuAdminForm(ModelForm): latitude = FloatField(min_value=-90, max_value=90, required=False) longitude = FloatField(min_value=-180, max_value=180, required=False) class Meta: model = Lieu exclude = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) geometry = self.initial.get('geometry', None) if isinstance(geometry, Point): self.initial['longitude'], self.initial['latitude'] = \ geometry.tuple def clean(self): data = super().clean() latitude = data.get('latitude') longitude = data.get('longitude') geometry = data.get('geometry') geometry_changed = geometry != self.initial.get('geometry') latlon_changed = (latitude != self.initial.get('latitude') or longitude != self.initial.get('longitude')) if latitude and longitude and latlon_changed \ and (not geometry or not geometry_changed): data['geometry'] = Point(longitude, latitude) return data
def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, "4.3500")) with translation.override("fr"): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n))
class DataForm(Form): District_Name = IntegerField() Season = IntegerField() Area = FloatField() temperature = FloatField() humidity = FloatField() ph = FloatField() rainfall = FloatField()
def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, '4.3500')) with translation.override('fr'), self.settings(USE_L10N=True): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n))
class BeaconForm(ModelForm): lat = FloatField() lng = FloatField() class Meta: model = Beacon fields = ('beacon_id', 'name', 'description', 'owner_group') def __init__(self, *args, **kwargs): super(BeaconForm, self).__init__(*args, **kwargs) self.fields['owner_group'].required = False
def __init__(self, *args, **kwargs): self.cid = kwargs.pop('course_id') self.course_id = Course.objects.get_record_by_id(self.cid) super().__init__(*args, **kwargs) YN = (('Tak', 'Tak'), ('Nie', 'Nie')) self.fields['if_cg'] = ChoiceField(choices=YN) self.fields['if_cg'].label = '1. Czy kurs jest częścią grupy kursów?' COURSES = ( ('ćwiczenia', 'ćwiczenia'), ('laboratorium', 'laboratorium'), ) self.fields['courses'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=COURSES, required=False) self.fields[ 'courses'].label = '2. Zaznacz formy, w których odbywają się zajęcia w ramach grupy kursów:' self.fields['weight_c'] = FloatField(min_value=0, max_value=1, required=False) self.fields[ 'weight_c'].label = '3. Wpisz udział oceny z ćwiczeń w ocenie końcowej z grupy kursów:' self.fields['weight_l'] = FloatField(min_value=0, max_value=1, required=False) self.fields[ 'weight_l'].label = '4. Wpisz udział oceny z laboratorium w ocenie końcowej z grupy kursów:' self.fields['weight_w'] = FloatField(min_value=0, max_value=1, required=False) self.fields[ 'weight_w'].label = '5. Wpisz udział oceny z wykładu w ocenie końcowej z grupy kursów:' self.fields['minimum'] = ChoiceField(choices=YN) self.fields[ 'minimum'].label = '6. Czy oceny z wszystkich kursów wchodzących w grupę muszą być większe niż 2?' for key in self.fields: self.fields[key].error_messages[ 'required'] = 'To pole jest wymagane.' if 'invalid' in self.fields[key].error_messages: self.fields[key].error_messages[ 'invalid'] = 'To nie jest poprawna wartość' if 'min_value' in self.fields[key].error_messages: self.fields[key].error_messages[ 'min_value'] = 'To nie jest poprawna wartość' if 'max_value' in self.fields[key].error_messages: self.fields[key].error_messages[ 'max_value'] = 'To nie jest poprawna wartość'
class SearchForm(Form): name = CharField(max_length=CHAR_FIELD_MAX_LEN_SHORT, required=False) source = CharField(max_length=CHAR_FIELD_MAX_LEN_SHORT, required=False) duration_unit = ChoiceField(choices=Recipe.TIME_UNITS) max_duration = FloatField(required=False) min_duration = FloatField(required=False) @staticmethod def _convert_time(x, unit_in, unit_out): # Convert the unit to days, then convert to desired unit days_coef = { Recipe.SEC: 1 / 86400, Recipe.MIN: 1 / 1440, Recipe.HRS: 1 / 24, Recipe.DAYS: 1, Recipe.WEEKS: 7, Recipe.MONTH: 365.5 / 12, Recipe.YEAR: 365.5 } if unit_in not in days_coef.keys() or unit_out not in days_coef.keys(): raise ValueError( "Time units have to be one of the time units supported by Recipe" ) return x * (days_coef[unit_in] / days_coef[unit_out]) def filtered_qs(self): """ Filter the Recipes that respond to the search. """ qs = Recipe.objects.all() if self.cleaned_data['name'] is not None: qs = qs.filter(name__icontains=self.cleaned_data['name']) if self.cleaned_data['source'] is not None: qs = qs.filter(source__icontains=self.cleaned_data['source']) if self.cleaned_data['max_duration'] is not None: ids = [ r.id for r in qs if r.total_time <= SearchForm._convert_time( self.cleaned_data['max_duration'], self.cleaned_data['duration_unit'], r.unit_time) ] qs = qs.filter(id__in=ids) if self.cleaned_data['min_duration'] is not None: ids = [ r.id for r in qs if r.total_time >= SearchForm._convert_time( self.cleaned_data['min_duration'], self.cleaned_data['duration_unit'], r.unit_time) ] qs = qs.filter(id__in=ids) return qs
class PartialStationForm(ModelForm): beacon = CharField() lat = FloatField() lng = FloatField() main_img_num = IntegerField(required=False) def __init__(self, *args, **kwargs): super(PartialStationForm, self).__init__(*args, **kwargs) for i in range(1, settings.MAX_IMGS_UPLOAD + 1): field_name = 'img{0}'.format(i) self.fields[field_name] = ImageField(required=False) class Meta: model = Station exclude = ['location']
class PortfolioForm(ModelForm): datum = DateField( widget=DateInput(attrs={'class': 'datepicker form-control'}), label=_('Datum')) simbol = ModelChoiceField(widget=Select(attrs={'class': 'form-control'}), label=_('Simbol'), queryset=Podjetje.objects.all()) vrednost = FloatField(widget=NumberInput(attrs={'class': 'form-control'}), label=_('Vrednost')) kolicina = FloatField(widget=NumberInput(attrs={'class': 'form-control'}), label=_('Količina')) class Meta: model = Portfolio fields = ['simbol', 'datum', 'vrednost', 'kolicina']
class ScheduleOccurrenceForm(Form): required_css_class = 'required' error_css_class = 'error' day = DayChoiceField(queryset=ConferenceDay.objects.none(), empty_label=None, required=True) time = ChoiceField(choices=conference_times, required=True) duration = FloatField(min_value=0.5, max_value=12, required=True, label=schedule_occurrence_labels['duration']) location = ModelChoiceField(queryset=Room.objects.all().order_by('name')) max_volunteer = IntegerField(required=True, initial=0) occurrence_id = IntegerField(required=False, widget=HiddenInput()) def __init__(self, *args, **kwargs): open_to_public = None if 'conference' in kwargs: conference = kwargs.pop('conference') else: conference = get_current_conference() if 'open_to_public' in kwargs: open_to_public = kwargs.pop('open_to_public') super(ScheduleOccurrenceForm, self).__init__(*args, **kwargs) self.fields['day'].queryset = get_conference_days( conference, open_to_public)
def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo( f, '<input step="any" type="number" name="f" id="id_f" required>') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1.0, f.clean("1")) self.assertIsInstance(f.clean("1"), float) self.assertEqual(23.0, f.clean("23")) self.assertEqual(3.1400000000000001, f.clean("3.14")) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("a") self.assertEqual(1.0, f.clean("1.0 ")) self.assertEqual(1.0, f.clean(" 1.0")) self.assertEqual(1.0, f.clean(" 1.0 ")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("1.0a") self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("Infinity") with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("NaN") with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("-Inf")
class DivForm(BSModalForm): date = DateTimeField( widget=DatePicker( options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ) ) sum = FloatField(required=True, min_value=0, widget=NumberInput(attrs={'type': 'number', 'step': "0.01"})) def __init__(self, *args, **kwargs): self.stock_id = kwargs.pop('stock_id') self.portfolio_id = kwargs.pop('portfolio_id') super(DivForm, self).__init__(*args, **kwargs) self.fields['sum'].required = True self.fields['date'].required = True def clean(self): self.instance.portfolio_id = self.portfolio_id self.instance.stock_id = self.stock_id return super(DivForm, self).clean() class Meta: model = Dividend exclude = ['stock', 'portfolio']
class InterventionBaseForm(CommonForm): infrastructure = forms.ModelChoiceField( required=False, queryset=Infrastructure.objects.existing(), widget=forms.HiddenInput()) signage = forms.ModelChoiceField(required=False, queryset=Signage.objects.existing(), widget=forms.HiddenInput()) length = FloatField(required=False, label=_("Length")) project = forms.ModelChoiceField(required=False, label=_("Project"), queryset=Project.objects.existing()) geomfields = ['topology'] leftpanel_scrollable = False topology = TopologyField(label="") fieldslayout = [ Div( HTML(""" <ul class="nav nav-tabs"> <li id="tab-main" class="active"><a href="#main" data-toggle="tab"><i class="icon-certificate"></i> %s</a></li> <li id="tab-advanced"><a href="#advanced" data-toggle="tab"><i class="icon-tasks"></i> %s</a></li> </ul>""" % (_("Main"), _("Advanced"))), Div( Div('structure', 'name', 'date', 'status', 'disorders', 'type', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'description', 'infrastructure', 'signage', css_id="main", css_class="tab-pane active"), Div( 'material_cost', 'heliport_cost', 'subcontract_cost', Fieldset(_("Mandays")), css_id= "advanced", # used in Javascript for activating tab if error css_class="tab-pane"), css_class="scrollable tab-content"), css_class="tabbable"), ] class Meta(CommonForm.Meta): model = Intervention fields = CommonForm.Meta.fields + \ ['structure', 'name', 'date', 'status', 'disorders', 'type', 'description', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'infrastructure', 'signage', 'material_cost', 'heliport_cost', 'subcontract_cost', 'topology']
def test_floatfield_2(self): f = FloatField(required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertEqual(1.0, f.clean('1')) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value)
def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo( f, '<input step="any" type="number" name="f" id="id_f" required />') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1.0, f.clean('1')) self.assertIsInstance(f.clean('1'), float) self.assertEqual(23.0, f.clean('23')) self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('a') self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0 ')) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('1.0a') self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('Infinity') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('NaN') with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean('-Inf')
class ExchangeRateForm(Form): """ Exchange rate form defining fields the base currency, target currency and a value to convert """ base = ModelChoiceField( queryset=Currency.objects.filter(abbr__in=settings.ACTUAL_CURRENCIES), initial=0, required=True, label=_('Base currency'), ) target = ModelChoiceField( queryset=Currency.objects.filter(abbr__in=settings.ACTUAL_CURRENCIES), initial=1, required=True, label=_('Target currency') ) value = FloatField( min_value=0, required=True, label=_('Value'), ) def clean(self): """Check if base and target are different currencies""" base = self.cleaned_data.get('base') target = self.cleaned_data.get('target') if base == target: raise ValidationError( _('Base and Target currencies have to be different!') )
class NewTransactionForm(Form): FREQUENCY_CHOICES = [(1, 'daily'), (2, 'weekly'), (3, 'monthly'), (4, 'yearly')] ENDS_HOW_CHOICES = [(1, 'end_date'), (2, 'never'), (3, 'n_transactions')] date = DateField(initial=datetime.date.today, widget=DateInput(attrs={ 'id': 'date-input', })) transaction_size = FloatField(widget=forms.NumberInput( attrs={'id': 'transaction-size-input'})) description = CharField(widget=forms.TextInput( attrs={'id': 'description-input'})) repeats = BooleanField( initial=False, required=False, widget=forms.CheckboxInput(attrs={'id': 'repeat-checkbox'})) frequency = ChoiceField(choices=FREQUENCY_CHOICES, required=False, widget=HiddenInput()) end_date = DateField(required=False, widget=HiddenInput()) ends_how = ChoiceField(choices=ENDS_HOW_CHOICES, required=False, widget=HiddenInput()) n_transactions = IntegerField(required=False, widget=HiddenInput())
class SearchFormTest(Form): # TODO: Create a field for ModelChoiceField STATUS_CHOICES = [ ('', 'All'), (True, 'Active'), (False, 'Inactive') ] field1 = CharField() field2 = TextInput() field3 = ChoiceField(choices=STATUS_CHOICES) field4 = BooleanField() field5 = DateField() field6 = DateTimeField() field7 = FloatField() field8 = DecimalField() field9 = IntegerField() field90 = CharField() field91 = CharField() def __init__(self, *args, **kwargs): super(SearchFormTest, self).__init__(*args, **kwargs) self.fields['field90'].label = "Date Start" self.fields['field91'].label = "Date End"
def get_form(self, form_class): stage_configurations = self.stage.get_queryset_configurations( prompt_me_for_input=True) form = form_class(**self.get_form_kwargs()) # We want to inject fields into the form for the configurations they've marked as prompt for config in stage_configurations: str_config_key = 'configuration_value_for_{}'.format(config.key) if config.data_type == config.BOOLEAN_TYPE: form.fields[str_config_key] = BooleanField(widget=Select( choices=((False, 'False'), (True, 'True')))) form.fields[str_config_key].coerce = lambda x: x == 'True', elif config.data_type == config.NUMBER_TYPE: form.fields[str_config_key] = FloatField() else: if config.sensitive_value: form.fields[str_config_key] = CharField( widget=PasswordInput) else: form.fields[str_config_key] = CharField() form.helper.layout.fields.insert( len(form.helper.layout.fields) - 1, str_config_key) return form
class DataForm(Form): friction_expression = CharField( max_length=100, label="Friction Expression" ) gravity_expression = CharField( max_length=100, label="Gravity Expression" ) plane_expression = CharField( max_length=100, label="Plane Expression" ) tick_time = FloatField( min_value=0, label="Tick Time" ) total_ticks = IntegerField( min_value=0, label="Total Ticks" ) start_point = IntegerField( label="Start Point" ) end_point = IntegerField( label="End Point" )
def test_floatfield_localized(self): """ A localized FloatField's widget renders to a text input without any number input specific attributes. """ f = FloatField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required />')
def __init__(self, request, filters): self.filters = filters # kwargs.pop('filters', None) super().__init__(request.POST) for filter in self.filters: field_name = filter['slug'] if filter['type'] == Attribute.TYPE_ENUM: self.fields[field_name] = MultipleChoiceField( required=False, choices=filter['choices'] ) if filter['type'] == Attribute.TYPE_SET: self.fields[field_name] = MultipleChoiceField( required=False, choices=filter['choices'] ) elif filter['type'] == Attribute.TYPE_BOOLEAN: self.fields[field_name] = NullBooleanField( required=False, ) elif filter['type'] == Attribute.TYPE_INTEGER: self.fields[field_name + '--min'] = IntegerField( required=False, min_value=filter['range_min'], max_value=filter['range_max'], ) self.fields[field_name + '--max'] = IntegerField( required=False, min_value=filter['range_min'], max_value=filter['range_max'], ) elif filter['type'] == Attribute.TYPE_FLOAT: self.fields[field_name + '--min'] = FloatField( required=False, localize=False, min_value=filter['range_min'], max_value=filter['range_max'], ) self.fields[field_name + '--max'] = FloatField( required=False, localize=False, min_value=filter['range_min'], max_value=filter['range_max'], ) elif filter['type'] == Attribute.TYPE_STRING: self.fields[field_name] = CharField( required=False, )
def get_form(self, form_class): stage_configurations = self.stage.get_queryset_configurations() form = form_class(**self.get_form_kwargs()) used_arg_names = [] # We want to inject fields into the form for the configurations they've marked as prompt for config in stage_configurations: if config.task_argument and config.task_name != self.task_name: continue if not config.prompt_me_for_input: if config.task_argument: used_arg_names.append(config.key) continue str_config_key = 'configuration_value_for_{}'.format(config.key) if config.data_type == config.BOOLEAN_TYPE: field = BooleanField(widget=Select(choices=((False, 'False'), (True, 'True')))) field.coerce=lambda x: x == 'True', elif config.data_type == config.NUMBER_TYPE: field = FloatField() else: field = CharField() if config.sensitive_value: field.widget = PasswordInput() if config.task_argument: used_arg_names.append(config.key) field.label = 'Argument value for ' + config.key field.initial = config.value form.fields[str_config_key] = field form.helper.layout.fields.insert(len(form.helper.layout.fields)-1, str_config_key) task_details = get_task_details(self.stage.project, self.task_name) for arg in task_details[2]: if isinstance(arg, tuple): name, default = arg else: name, default = arg, None if name in used_arg_names: continue str_config_key = 'configuration_value_for_{}'.format(name) field = CharField(label='Argument value for ' + name, initial=default) form.fields[str_config_key] = field form.helper.layout.fields.insert(len(form.helper.layout.fields)-1, str_config_key) return form
class FenomenoForm(ModelForm): longitude = FloatField() latitude = FloatField() class Meta: model = Fenomeno fields = ('nome', 'data', 'hora', 'latitude', 'longitude') def clean(self): cleaned_data = super().clean() lon = cleaned_data.get('longitude') lat = cleaned_data.get('latitude') cleaned_data['geom'] = Point((lon, lat)) if not cleaned_data['geom'].is_valid: raise ValidationError('Geometria inválida') return cleaned_data
def __init__(self, parent_puzzle: Puzzle, *args, **kwargs): super(HiddenPartsPositionForm, self).__init__(*args, **kwargs) for i, parts in enumerate(parent_puzzle.parts.all()): self.fields['parts-left{num}'.format(num=i)] = FloatField( label=parts.name + '-left', initial=0.0, widget=HiddenInput(attrs={ 'class': 'no-spinners form-control', }, ), required=True) self.fields['parts-top{num}'.format(num=i)] = FloatField( label=parts.name + '-top', initial=0.0, widget=HiddenInput(attrs={ 'class': 'no-spinners form-control', }, ), required=True)
class Meta: model = Vulnerability fields = '__all__' cvss_value = FloatField(min_value=0, max_value=10) report_page = FloatField(min_value=0) widgets = { 'perimeter': Select(), 'synopsis': Textarea(attrs={'cols':30,'rows':5,'wrap':"hard"}), 'identification_date': DateInput(), 'remediation_deadline': DateInput(), 'remediation': Textarea(attrs={'cols':30,'rows':5,'wrap':"hard"}), 'observation': Textarea(attrs={'cols':30,'rows':5,'wrap':"hard"}), 'cvss_value': NumberInput(attrs={'min':0, 'max':10}), 'report_page': NumberInput(attrs={'min':0}) }
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["actual_time"] = FloatField() self.fields[ "actual_time"].label = "Faktyczny czas wykonania (w minutach)" for key in self.fields: self.fields[key].error_messages[ 'required'] = "To pole jest wymagane."
def create(self, field): constraints = self._get_number_constraints(field) float_field = FloatField(label=field.label, initial=field.value, required=field.is_required(), help_text=field.instruction, widget=TextInputForFloat, **constraints) float_field.widget.attrs["watermark"] = self._get_number_field_constraint_text(field) float_field.widget.attrs['style'] = 'padding-top: 7px;' return float_field