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_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))
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))
def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo( f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" required />', ) with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): f.clean('1.6') with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): f.clean('0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5)
def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo(f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" />') with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): f.clean('1.6') with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): f.clean('0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5)
class SearchFormBase(Form): threshold = ChoiceField(choices=[(25,25),(90,90)], required=False) resolutionMin = FloatField(required=False, min_value=0, initial=0, widget=TextInput(attrs={'size':3})) resolutionMax = FloatField(required=False, min_value=0, initial=1.2, widget=TextInput(attrs={'size':3})) rfactorMin = FloatField(required=False, min_value=0, initial=0, widget=TextInput(attrs={'size':3})) rfactorMax = FloatField(required=False, min_value=0, initial=0.25, widget=TextInput(attrs={'size':3})) rfreeMin = FloatField(required=False, min_value=0, initial=0, widget=TextInput(attrs={'size':3})) rfreeMax = FloatField(required=False, min_value=0, initial=0.30, widget=TextInput(attrs={'size':3})) proteins = CharField(required=False) proteins_i = IntegerField(required=False, widget=HiddenInput(attrs={'class':'include'})) residues = ChoiceField(choices=[(i,i) for i in range(1, settings.SEGMENT_SIZE+1)], initial=3)
class ProfForm(ModelForm): stars = FloatField(required=False, max_value=5, min_value=-1, initial=4.5, label="stars (-1 = deactivate)", widget=NumberInput(attrs={ 'id': 'form_starts', 'step': '0.5' })) class Meta: model = Proof fields = '__all__' exclude = [ 'owner', ]
class QueryForm(forms.Form): """ We don't really need a form, but if we use one django will do all the grunt work of converting strings to numbers and booleans e.t.c """ FORM_CLASSES = {} target_index = CharField(required=True) dataparallel = CharField(required=True) batch = IntegerField(required=True) benchmark = CharField(required=True) collection = CharField(required=True) expid = CharField(required=True) fold = CharField(required=True) index = CharField(required=True) indexstops = BooleanField(required=False) itersize = IntegerField(required=True) lr = FloatField(required=True) maxdoclen = IntegerField(required=True) maxqlen = IntegerField(required=True) reranker = CharField(required=True) niters = IntegerField(required=True) predontrain = BooleanField(required=False) searcher = CharField(required=True) rundocsonly = BooleanField(required=False) sample = CharField(required=True) seed = IntegerField(required=True) softmaxloss = BooleanField(required=False) stemmer = CharField(required=True) query = CharField(required=True) gradacc = IntegerField(required=True) @classmethod def register(cls, formcls): name = formcls.name if name in cls.FORM_CLASSES and cls.FORM_CLASSES[name] != formcls: raise RuntimeError( f"encountered two Forms with the same name: {name}") cls.FORM_CLASSES[name] = formcls return formcls
class AllFieldTypesForm(Form): char = CharField() int_ = IntegerField() date = DateField() time = TimeField() datetime_ = DateTimeField() regex = RegexField(regex='^[a-f]{3}$') email = EmailField() file = FileField() # image = ImageField() url = URLField() bool = BooleanField() nullbool = NullBooleanField() choice = ChoiceField(choices=(('test choice', 'yay test choice'), )) multichoice = MultipleChoiceField(choices=( ('test choice', 'yay test choice'), ('test choice 2', 'yay another choice'), ('test choice 3', 'yay test choice'), )) float = FloatField() decimal = DecimalField() ip = IPAddressField() generic_ip = GenericIPAddressField() filepath = FilePathField(path=tempfile.gettempdir(), allow_files=True, allow_folders=True) slug = SlugField() typed_choice = TypedChoiceField(choices=( (1, 'test'), (2, 'test 2'), (3, 'bah'), ), coerce=int) typed_multichoice = TypedMultipleChoiceField(choices=( (1, 'test'), (2, 'test 2'), (3, 'bah'), ), coerce=int) model_choice = ModelChoiceField(queryset=get_user_model().objects.all()) model_multichoice = ModelMultipleChoiceField( queryset=get_user_model().objects.all())
class TestSearchForm(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(TestSearchForm, self).__init__(*args, **kwargs) self.fields['field90'].label = "Date Start" self.fields['field91'].label = "Date End"
class ScheduleBasicForm(ModelForm): required_css_class = 'required' error_css_class = 'error' day = ChoiceField(choices=['No Days Specified']) time = ChoiceField(choices=conference_times) location = ModelChoiceField(queryset=Room.objects.all().order_by('name')) max_volunteer = IntegerField(required=True) duration = FloatField(min_value=0.5, max_value=12, required=True) class Meta: model = Event fields = [ 'e_title', 'e_description', 'duration', 'max_volunteer', 'day', 'time', 'location', ] def __init__(self, *args, **kwargs): if 'instance' in kwargs: conference = kwargs['instance'].e_conference if 'initial' in kwargs and 'duration' not in kwargs['initial']: kwargs['initial']['duration'] = float( kwargs['instance'].duration.total_seconds()) / 3600 else: conference = kwargs.pop('conference') super(ScheduleBasicForm, self).__init__(*args, **kwargs) self.fields['day'] = ModelChoiceField( queryset=conference.conferenceday_set.all()) self.fields['location'] = ModelChoiceField( queryset=Room.objects.filter(conferences=conference)) def clean_duration(self): data = timedelta(minutes=self.cleaned_data['duration'] * 60) return data
def __init__(self, *args, **kwargs): dim = kwargs.pop('dim', 1) choices = kwargs.pop('choices', None) if not isinstance(dim, (int, long)) or (dim < 1): raise ValidationError(self.error_messages['invalid_dim']) if not is_iterable(choices) or \ any(not is_iterable(c) for c in choices) or \ any(not isinstance(c[0], ureg.Unit) for c in choices): raise ValidationError(self.error_messages['invalid_choices']) if any(c[0].dimensionality != choices[0][0].dimensionality for c in choices): raise ValidationError(self.error_messages['different_units']) fields = [FloatField() for i in range(dim)] + [ChoiceField(choices=[(str(u), c) for u, c in choices])] kwargs.update({ 'widget': MultiQuantityWidget(dim=dim, choices=choices) }) super(MultiQuantityFormField, self).__init__(fields, *args, **kwargs)
def test_decimalfield_support_decimal_separator(self): f = FloatField(localize=True) self.assertEqual(f.clean('1001,10'), 1001.10) self.assertEqual(f.clean('1001.10'), 1001.10)
def test_decimalfield_support_thousands_separator(self): f = FloatField(localize=True) self.assertEqual(f.clean('1.001,10'), 1001.10) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean('1,001.1')
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
def fill_edit(self): enum_form = { 'ACTIV': 'aktywność', 'EXAM': 'egzamin', 'QUIZ': 'kartkówka', 'TEST': 'kolokwium', 'LIST': 'lista zadań' } enum_type = {'PKT': 'punkty', 'PERC': 'procenty', 'MARK': 'ocena'} FORMS = (('aktywność', 'aktywność'), ('egzamin', 'egzamin'), ('kartkówka', 'kartkówka'), ('kolokwium', 'kolokwium'), ('lista zadań', 'lista zadań')) TYPES = ( ('punkty', 'punkty'), ('ocena', 'ocena'), ('procenty', 'procenty'), ) YN = (('Tak', 'Tak'), ('Nie', 'Nie')) comp = Components.objects.get_records_by_course_id(self.course_id) ects = self.course_id.ECTS mod = Modyfication.objects.get_records_by_course_id(self.course_id) i = 1 self.fields['ects'] = IntegerField(min_value=0, max_value=30, initial=ects) self.fields[ 'ects'].label = '{0:d}. Wpisz ile punktów ECTS ma kurs:'.format(i) i += 1 init_comp = [] for c in comp: init_comp.append(enum_form[c.form]) self.fields['formy'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=FORMS, initial=init_comp) self.fields[ 'formy'].label = '{0:d}. Wybierz formy uzyskania ocen cząstkowych na kursie:'.format( i) i += 1 c = enum_type[comp[0].type] self.fields['form_type'] = ChoiceField(choices=TYPES, required=False, initial=c) self.fields[ 'form_type'].label = '{0:d}. Zaznacz rodzaj oceniania na kursie:'.format( i) i += 1 self.fields['mod_plus'] = ChoiceField(choices=YN, initial='Nie') self.fields['mod_plus_w'] = FloatField(min_value=0, required=False) if mod: for m in mod: if m.mod == 'PLUS': self.fields['mod_plus'] = ChoiceField(choices=YN, initial='Tak') self.fields['mod_plus_w'] = FloatField(min_value=0, required=False, initial=m.val) self.fields[ 'mod_plus'].label = '{0:d}. Czy możliwe jest podwyższenie oceny?'.format( i) i += 1 self.fields[ 'mod_plus_w'].label = 'Wpisz o ile ocena może zostać podwyższona:' self.fields['mod_minus'] = ChoiceField(choices=YN, initial='Nie') self.fields['mod_minus_w'] = FloatField(min_value=0, required=False) self.fields['mod_type'] = ChoiceField(choices=TYPES, required=False) if mod: for m in mod: if m.mod == 'MINUS': self.fields['mod_minus'] = ChoiceField(choices=YN, initial='Tak') t = enum_type[m.type] self.fields['mod_minus_t'] = ChoiceField(choices=TYPES, required=False, initial=t) self.fields['mod_type'] = ChoiceField(choices=TYPES, required=False, initial=m.val) self.fields[ 'mod_minus'].label = '{0:d}. Czy możliwe jest obniżenie oceny?'.format( i) i += 1 self.fields[ 'mod_minus_w'].label = 'Wpisz o ile ocena może zostać obniżona:' self.fields[ 'mod_type'].label = '{0:d}. Wybierz w jakim typie jest modyfikacja oceny:'.format( i) i += 1
class FloatInputAnswer(BaseAnswerForm): answer = FloatField()
class UploadForm(MoneypitForm): longitude = FloatField(required=False) latitude = FloatField(required=False) image = CharField() def __init__(self, *args, **kwargs): self.wealth = kwargs.pop('wealth', None) super(UploadForm, self).__init__(*args, **kwargs) def clean_latitude(self): latitude = self.cleaned_data['latitude'] if not latitude: return 0 if latitude < -90 or latitude > 90: raise ValidationError('Invalid latitude') return latitude def clean_longitude(self): longitude = self.cleaned_data['longitude'] if not longitude: return 0 if longitude < -180 or longitude > 180: raise ValidationError('Invalid longitude') return longitude def clean_image(self): receipts = Receipt.objects.filter(wealth=self.wealth) if len(receipts) > MAX_RECEIPTS: raise ValidationError('You have reached you receipt limit') image64 = self.cleaned_data['image'] if len(image64) > MAX_RECEIPT_SIZE: raise ValidationError('Receipt too large') try: decoded = decodestring(image64) content = StringIO(decoded) img = Image.open(content) except TypeError: raise ValidationError('Invalid base64 data') except IOError: raise ValidationError('Not a JPEG image') if img.format != 'JPEG': raise ValidationError('Only JPEGs are supported') if (img.size[0] > MAX_RECEIPT_DIMENSION or img.size[1] > MAX_RECEIPT_DIMENSION): try: img.thumbnail( (MAX_RECEIPT_DIMENSION, MAX_RECEIPT_DIMENSION), Image.ANTIALIAS) except IOError: raise ValidationError('Couldn\t scale receipt, abandoning') return img def save(self): img = self.cleaned_data['image'] temp_handle = StringIO() img.save(temp_handle, 'jpeg') temp_handle.seek(0) filename = '%s.%s' % (uuid4(), 'jpeg') suf = SimpleUploadedFile( filename, temp_handle.read(), content_type='image/jpeg') receipt = Receipt( image = suf, date = datetime.now(), wealth = self.wealth, longitude = self.cleaned_data['longitude'], latitude = self.cleaned_data['latitude']) receipt.save()
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 SetCounterValForm(Form): counter_id = CharField(label="Ідентифікатор Лічильника", max_length=500, required=True, error_messages={'required': "Це поле є обов'язковим"}, help_text="Номер присвоєний лічильнику водоканалом") counter_val = FloatField(label="Значення Показника", required=True, min_value=0, error_messages={'required': "Це поле є обов'язковим"}, help_text="Поточне значення лічильнику") def __init__(self, *args, **kwargs): self.user_id = kwargs.get('initial').pop("user_id") super().__init__(*args, **kwargs) self.fields['counter_id'].widget.attrs['class'] = "form-control" self.fields['counter_id'].widget = HiddenInput() self.fields['counter_val'].widget.attrs['class'] = "form-control" def clean(self): '''Method validates form fields''' form_data = self.cleaned_data counter_pk = form_data.get("counter_id") user_id = self.user_id db_handler = DbSyncHandler() contracts_list = db_handler._get_sql_user_contracts_by_id(user_id, counter_pk) if contracts_list: contracts = contracts_list[0] origin_user = contracts["contract"].user if origin_user==user_id: counter_vals = contracts["value"] if counter_vals: if counter_vals.value_vodocanal: last_val = counter_vals.value_vodocanal else: last_val = None counter_val = form_data.get("counter_val") if last_val: vals_diff = counter_val - last_val if last_val > counter_val: self._errors["counter_val"] =\ ['Показник не може бути нижчим за існуючий Для внесення корективів тел.: +38 097 281 47 28'] write_log(user=user_id, place="Подання Показника", msg_type="Невдало", message="Невдала спроба подати показник {} (останній зареєстрований показник {})".format(counter_val, last_val)) if vals_diff >= 100: self._errors["counter_val"] =\ ['Введений показник занадто великий у порівнянні із попереднім'] write_log(user=user_id, place="Подання Показника", msg_type="Невдало", message="Невдала спроба подати показник {} (останній зареєстрований показник {})".format(counter_val, last_val)) else: self._errors["counter_val"] = \ ['Некоректний номер лічильника. Спробуйте влогуватись і знову залогуватись!'] else: self._errors["counter_val"] = \ ['Некоректний номер лічильника. Спробуйте влогуватись і знову залогуватись!'] return form_data
def fill_edit(self): YN = (('Tak', 'Tak'), ('Nie', 'Nie')) COURSES = ( ('ćwiczenia', 'ćwiczenia'), ('laboratorium', 'laboratorium'), ) cg = CourseGroup.objects.get_records_by_course_id(self.course_id) group = False if cg.exists(): group = True comp = Components.objects.get_records_by_course_id(self.course_id) ects = self.course_id.ECTS mod = Modyfication.objects.get_records_by_course_id(self.course_id) if group: self.fields['if_cg'] = ChoiceField(choices=YN, initial="Tak") else: self.fields['if_cg'] = ChoiceField(choices=YN, initial="Nie") self.fields['if_cg'].label = '1. Czy kurs jest częścią grupy kursów?' my_list = [] weight_list = [("", ""), ("", ""), ("", "")] all_types = Course.objects.get_all_types_by_id(self.course_id.id) if all_types: for el in all_types: if group: if el.type == "C": my_list.append("ćwiczenia") weight_list[0] = (el.coursegroup.weight, el.coursegroup.minimum) if el.type == "L": my_list.append("laboratorium") weight_list[1] = (el.coursegroup.weight, el.coursegroup.minimum) if el.type == "W": weight_list[2] = (el.coursegroup.weight, el.coursegroup.minimum) self.fields['courses'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=COURSES, required=False, initial=my_list) 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, initial=weight_list[0][0]) 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, initial=weight_list[1][0]) 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, initial=weight_list[2][0]) self.fields[ 'weight_w'].label = '5. Wpisz udział oceny z wykładu w ocenie końcowej z grupy kursów:' if weight_list[0] != " " and weight_list[0][1]: self.fields['minimum'] = ChoiceField(choices=YN, initial="Tak") else: self.fields['minimum'] = ChoiceField(choices=YN, initial="Nie") self.fields[ 'minimum'].label = '6. Czy oceny z wszystkich kursów wchodzących w grupę muszą być większe niż 2?'
class GearFinderForm(forms.Form): gear_set = ModelChoiceField(GearSet.objects.all(), required=True, initial=-1) target = FloatField(label="Required Ratio") tolerance = FloatField(initial=0.00009)
class PointForm(Form): nome = CharField(max_length=100, required=False) lat = FloatField(label="Latitude") lon = FloatField(label="Longitude")
class InterventionForm(CommonForm): """ An intervention can be a Point or a Line """ topology = TopologyField(label="") infrastructure = forms.ModelChoiceField( required=False, queryset=BaseInfrastructure.objects.existing(), widget=forms.HiddenInput()) length = FloatField(required=False, label=_("Length")) leftpanel_scrollable = False 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>""" % (unicode(_("Main")), unicode(_("Advanced")))), Div( Div('name', 'date', 'status', 'disorders', 'type', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'description', 'infrastructure', 'pk', 'model', 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"), ] geomfields = ['topology'] class Meta(CommonForm.Meta): model = Intervention fields = CommonForm.Meta.fields + \ ['structure', 'name', 'date', 'status', 'disorders', 'type', 'description', 'subcontracting', 'length', 'width', 'height', 'stake', 'project', 'infrastructure', 'material_cost', 'heliport_cost', 'subcontract_cost', 'topology'] def __init__(self, *args, **kwargs): super(InterventionForm, self).__init__(*args, **kwargs) # If we create or edit an intervention on infrastructure, set # topology field as read-only infrastructure = kwargs.get('initial', {}).get('infrastructure') if self.instance.on_infrastructure: infrastructure = self.instance.infrastructure self.fields['infrastructure'].initial = infrastructure if infrastructure: self.helper.form_action += '?infrastructure=%s' % infrastructure.pk self.fields['topology'].required = False self.fields['topology'].widget = TopologyReadonlyWidget() self.fields['topology'].label = '%s%s %s' % ( self.instance.infrastructure_display, unicode(_("On %s") % _(infrastructure.kind.lower())), u'<a href="%s">%s</a>' % (infrastructure.get_detail_url(), unicode(infrastructure))) # Length is not editable in AltimetryMixin self.fields['length'].initial = self.instance.length editable = bool(self.instance.geom and self.instance.geom.geom_type == 'Point') self.fields['length'].widget.attrs['readonly'] = editable def clean(self, *args, **kwargs): # If topology was read-only, topology field is empty, get it from infra. cleaned_data = super(InterventionForm, self).clean() topology_readonly = self.cleaned_data.get('topology', None) is None if topology_readonly and 'infrastructure' in self.cleaned_data: self.cleaned_data['topology'] = self.cleaned_data['infrastructure'] return cleaned_data def save(self, *args, **kwargs): self.instance.length = self.cleaned_data.get('length') infrastructure = self.cleaned_data.get('infrastructure') if infrastructure: self.instance.set_infrastructure(infrastructure) return super(InterventionForm, self).save(*args, **kwargs)
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 InterventionForm(CommonForm): """ An intervention can be a Point or a Line """ topology = TopologyField(label="") length = FloatField(required=False, label=_("Length")) project = forms.ModelChoiceField(required=False, label=_("Project"), queryset=Project.objects.existing()) geomfields = ['topology'] leftpanel_scrollable = False 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', 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', 'material_cost', 'heliport_cost', 'subcontract_cost', 'topology'] def __init__(self, *args, target_type=None, target_id=None, **kwargs): super(InterventionForm, self).__init__(*args, **kwargs) if not self.instance.pk: # New intervention. We have to set its target. if target_type and target_id: # Point target to an existing topology ct = ContentType.objects.get_for_id(target_type) self.instance.target = ct.get_object_for_this_type( id=target_id) # Set POST URL self.helper.form_action += '?target_type={}&target_id={}'.format( target_type, target_id) else: # Point target to a new topology self.instance.target = Topology(kind='INTERVENTION') # Else: existing intervention. Target is already set self.fields['topology'].initial = self.instance.target if self.instance.target.__class__ == Topology: # Intervention has its own topology title = _("On {}".format(_("Paths"))) self.fields['topology'].label = \ '<img src="{prefix}images/path-16.png" title="{title}">{title}'.format( prefix=settings.STATIC_URL, title=title ) else: # Intervention on an existing topology icon = self.instance.target._meta.model_name title = _("On {}".format(str(self.instance.target))) self.fields['topology'].label = \ '<img src="{prefix}images/{icon}-16.png" title="{title}"><a href="{url}">{title}</a>'.format( prefix=settings.STATIC_URL, icon=icon, title=title, url=self.instance.target.get_detail_url() ) # Topology is readonly del self.fields['topology'] # Length is not editable in AltimetryMixin self.fields['length'].initial = self.instance.length editable = bool(self.instance.geom and (self.instance.geom.geom_type == 'Point' or self.instance.geom.geom_type == 'LineString')) self.fields['length'].widget.attrs['readonly'] = editable def save(self, *args, **kwargs): target = self.instance.target if not target.pk: target.save() topology = self.cleaned_data.get('topology') if topology and topology.pk != target.pk: target.mutate(topology) intervention = super().save(*args, **kwargs, commit=False) intervention.target = target intervention.save() self.save_m2m() return intervention
class QueryBuilderForm(forms.Form): """ Form to build an SQL query using a web interface. Works hand in hand with ``querybuilder.js`` on the client side; q.v. """ database = CharField(label="Schema", required=False) schema = CharField(label="Schema", required=True) table = CharField(label="Table", required=True) column = CharField(label="Column", required=True) datatype = CharField(label="Data type", required=True) offer_where = BooleanField(label="Offer WHERE?", required=False) # BooleanField generally needs "required=False", or you can't have False! where_op = CharField(label="WHERE comparison", required=False) date_value = DateField(label="Date value (e.g. 1900-01-31)", required=False) int_value = IntegerField(label="Integer value", required=False) float_value = FloatField(label="Float value", required=False) string_value = CharField(label="String value", required=False) file = FileField(label="File (for IN)", required=False) def __init__(self, *args, **kwargs) -> None: self.file_values_list = [] # type: List[Any] super().__init__(*args, **kwargs) def get_datatype(self) -> Optional[str]: return self.data.get('datatype', None) def is_datatype_unknown(self) -> bool: return self.get_datatype() == QB_DATATYPE_UNKNOWN def offering_where(self) -> bool: if self.is_datatype_unknown(): return False return self.data.get('offer_where', False) def get_value_fieldname(self) -> str: datatype = self.get_datatype() if datatype == QB_DATATYPE_INTEGER: return "int_value" if datatype == QB_DATATYPE_FLOAT: return "float_value" if datatype == QB_DATATYPE_DATE: return "date_value" if datatype in QB_STRING_TYPES: return "string_value" if datatype == QB_DATATYPE_UNKNOWN: return "" raise ValueError("Invalid field type") def get_cleaned_where_value(self) -> Any: # Only call this if you've already cleaned/validated the form! return self.cleaned_data[self.get_value_fieldname()] def clean(self) -> None: # Check the WHERE information is sufficient. if 'submit_select' in self.data or 'submit_select_star' in self.data: # Form submitted via the "Add" method, so no checks required. # http://stackoverflow.com/questions/866272/how-can-i-build-multiple-submit-buttons-django-form # noqa return if not self.offering_where(): return cleaned_data = super().clean() if not cleaned_data['where_op']: self.add_error('where_op', forms.ValidationError("Must specify comparison")) # No need for a value for NULL-related comparisons. But otherwise: where_op = cleaned_data['where_op'] if where_op not in SQL_OPS_VALUE_UNNECESSARY + SQL_OPS_MULTIPLE_VALUES: # Can't take 0 or many parameters, so need the standard single # value: value_fieldname = self.get_value_fieldname() value = cleaned_data.get(value_fieldname) if not value: self.add_error( value_fieldname, forms.ValidationError("Must specify WHERE condition")) # --------------------------------------------------------------------- # Special processing for file upload operations # --------------------------------------------------------------------- if where_op not in SQL_OPS_MULTIPLE_VALUES: return fileobj = cleaned_data['file'] # ... is an instance of InMemoryUploadedFile if not fileobj: self.add_error('file', forms.ValidationError("Must specify file")) return datatype = self.get_datatype() if datatype in QB_STRING_TYPES: form_to_python_fn = str elif datatype == QB_DATATYPE_DATE: form_to_python_fn = html_form_date_to_python elif datatype == QB_DATATYPE_INTEGER: form_to_python_fn = int_validator elif datatype == QB_DATATYPE_FLOAT: form_to_python_fn = float_validator else: # Safe defaults form_to_python_fn = str # Or: http://www.dabeaz.com/generators/Generators.pdf self.file_values_list = [] # type: List[Any] for line in fileobj.read().decode("utf8").splitlines(): raw_item = line.strip() if not raw_item or raw_item.startswith('#'): continue try: value = form_to_python_fn(raw_item) except (TypeError, ValueError): self.add_error('file', forms.ValidationError( f"File contains bad value: {raw_item!r}")) return self.file_values_list.append(value) if not self.file_values_list: self.add_error('file', forms.ValidationError( "No values found in file"))
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) FORMS = (('aktywność', 'aktywność'), ('egzamin', 'egzamin'), ('kartkówka', 'kartkówka'), ('kolokwium', 'kolokwium'), ('lista zadań', 'lista zadań')) TYPES = ( ('punkty', 'punkty'), ('ocena', 'ocena'), ('procenty', 'procenty'), ) i = 1 self.fields['ects'] = IntegerField(min_value=0, max_value=30) self.fields[ 'ects'].label = '{0:d}. Wpisz ile punktów ECTS ma kurs:'.format(i) i += 1 self.fields['formy'] = MultipleChoiceField( widget=CheckboxSelectMultiple, choices=FORMS) self.fields[ 'formy'].label = '{0:d}. Wybierz formy uzyskania ocen cząstkowych na kursie:'.format( i) i += 1 self.fields['form_type'] = ChoiceField(choices=TYPES, required=False) self.fields[ 'form_type'].label = '{0:d}. Zaznacz rodzaj oceniania na kursie:'.format( i) i += 1 YN = (('Tak', 'Tak'), ('Nie', 'Nie')) self.fields['mod_plus'] = ChoiceField(choices=YN) self.fields[ 'mod_plus'].label = '{0:d}. Czy możliwe jest podwyższenie oceny?'.format( i) i += 1 self.fields['mod_plus_w'] = FloatField(min_value=0, required=False) self.fields[ 'mod_plus_w'].label = 'Wpisz o ile ocena może zostać podwyższona:' self.fields['mod_minus'] = ChoiceField(choices=YN) self.fields[ 'mod_minus'].label = '{0:d}. Czy możliwe jest obniżenie oceny?'.format( i) i += 1 self.fields['mod_minus_w'] = FloatField(min_value=0, required=False) self.fields[ 'mod_minus_w'].label = 'Wpisz o ile ocena może zostać obniżona:' self.fields['mod_type'] = ChoiceField(choices=TYPES, required=False) self.fields[ 'mod_type'].label = '{0:d}. Wybierz w jakim typie jest modyfikacja oceny:'.format( i) i += 1 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 EventForm(ModelForm): name = CharField(max_length=85, widget=TextInput(attrs={ 'placeholder': 'Enter event name', 'tabindex': 1 })) type = ModelChoiceField(queryset=EventType.objects.all(), widget=Select(attrs={'tabindex': 2}), empty_label="select event type") is_public = TypedChoiceField(coerce=boolean_coerce, choices=PUBLIC_PRIVATE_BOOLEAN_CHOICES, initial=True, widget=RadioSelect( renderer=RadioSelectTableRenderer, attrs={'tabindex': 3})) is_drop = TypedChoiceField(coerce=boolean_coerce, choices=DROP_BOOLEAN_CHOICES, initial=False, widget=RadioSelect( renderer=RadioSelectTableRenderer, attrs={'tabindex': 4})) location = CharField(widget=TextInput( attrs={ 'autocomplete': 'off', 'placeholder': 'Enter classroom #, address, etc..', 'tabindex': 5 }), required=False) latitude = FloatField(widget=HiddenInput, required=False) longitude = FloatField(widget=HiddenInput, required=False) description = CharField(widget=CKEditorWidget(attrs={'tabindex': 6})) start_datetime = DateTimeField( label="Start Date/Time:", widget=ImprovedSplitDateTimeWidget(attrs={'tabindex': 7}), required=False) end_datetime = DateTimeField( label="End Date/Time:", widget=ImprovedSplitDateTimeWidget(attrs={'tabindex': 8}), required=False) audience = ModelMultipleChoiceField( label="Intended Audience:", widget=SelectMultiple(attrs={'tabindex': 9}), queryset=SchoolYear.objects.all(), required=False) rsvp_message = CharField( label="RSVP Message:", widget=Textarea(attrs={ 'tabindex': 10, 'placeholder': 'Tell RSVPs what to wear, bring, etc..' }), required=False) class Meta: fields = ('name', 'start_datetime', 'end_datetime', 'type', 'short_slug', 'is_drop', 'location', 'latitude', 'longitude', 'audience', 'description', 'rsvp_message', 'is_public') model = Event def clean_end_datetime(self): if self.cleaned_data['end_datetime'] and self.cleaned_data[ 'end_datetime'] < datetime.now(): raise ValidationError(_("End date/time must be in the future.")) return self.cleaned_data['end_datetime'] def clean(self): if not self.cleaned_data["type"] == EventType.objects.get( name="Rolling Deadline") and not self.cleaned_data[ "type"] == EventType.objects.get(name="Hard Deadline"): if not self.cleaned_data['start_datetime']: raise ValidationError(_(m.start_datetime_required)) elif not self.cleaned_data["type"] == EventType.objects.get( name="Rolling Deadline"): if not self.cleaned_data['end_datetime']: raise ValidationError(_(m.end_datetime_required)) return self.cleaned_data
class AllocateForm(Form): choice = ModelChoiceField(queryset=Game.objects.filter(ready=None)) amount = FloatField()
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 LookupForm(Form): latitude = FloatField() longitude = FloatField() distance = FloatField()
def test_floatfield_widget_attrs(self): f = FloatField(widget=NumberInput(attrs={'step': 0.01, 'max': 1.0, 'min': 0.0})) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" required />', )