def clean(self): for task in self.instance.all_tasks.all(): if task.is_time_and_materials: for li in task.lineitems.all(): expended = self.data.get("li-{}-complete".format(li.id), None) if expended is None: self.add_error(None, _("Inconsistent state.")) return expended = formats.sanitize_separators(expended) value = str(expended).strip() try: Decimal(value) except: self.add_error(None, _("Invalid decimal.")) else: complete = self.data.get("task-{}-complete".format(task.id), None) if complete is None: self.add_error(None, _("Inconsistent state.")) return complete = formats.sanitize_separators(complete) value = str(complete).strip() try: Decimal(value) except: self.add_error(None, _("Invalid decimal."))
def to_python(self, value): value = super(BBoxField, self).to_python(value) if not value: return -180.0, -90.0, 180.0, 90.0 try: lx, ly, ux, uy = value.split(',') if self.localize: lx = float(sanitize_separators(lx)) ly = float(sanitize_separators(ly)) ux = float(sanitize_separators(ux)) uy = float(sanitize_separators(uy)) if uy < ly or ux < lx: raise ValidationError( "BBoxes must be in lower-left(x,y), upper-right(x,y) order" ) except (ValueError, TypeError): raise ValidationError( "BBoxes must be four floating point values separated by commas" ) lx = float(sanitize_separators(lx)) ly = float(sanitize_separators(ly)) ux = float(sanitize_separators(ux)) uy = float(sanitize_separators(uy)) return lx, ly, ux, uy
def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. Truncates the value to 7 decimals. """ data = smart_text(data).strip() if self.localize: data = sanitize_separators(data) if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') # Truncate the value if needed max_exp = self.decimal_places s, d, e = value.as_tuple() if abs(e) > max_exp: d = d[:e] + d[e:][:max_exp] value = decimal.Decimal([s, d, -max_exp]) return self.quantize(self.validate_precision(value))
def clean_answer(self, answer): if self.required: if not answer or (self.type == Question.TYPE_BOOLEAN and answer not in ("true", "True", True)): raise ValidationError( _('An answer to this question is required to proceed.')) if not answer: if self.type == Question.TYPE_BOOLEAN: return False return None if self.type == Question.TYPE_CHOICE: try: return self.options.get(pk=answer) except: raise ValidationError(_('Invalid option selected.')) elif self.type == Question.TYPE_CHOICE_MULTIPLE: try: if isinstance(answer, str): return list(self.options.filter(pk__in=answer.split(","))) else: return list(self.options.filter(pk__in=answer)) except: raise ValidationError(_('Invalid option selected.')) elif self.type == Question.TYPE_BOOLEAN: return answer in ('true', 'True', True) elif self.type == Question.TYPE_NUMBER: answer = formats.sanitize_separators(answer) answer = str(answer).strip() try: return Decimal(answer) except DecimalException: raise ValidationError(_('Invalid number input.')) elif self.type == Question.TYPE_DATE: if isinstance(answer, date): return answer try: return dateutil.parser.parse(answer).date() except: raise ValidationError(_('Invalid date input.')) elif self.type == Question.TYPE_TIME: if isinstance(answer, time): return answer try: return dateutil.parser.parse(answer).time() except: raise ValidationError(_('Invalid time input.')) elif self.type == Question.TYPE_DATETIME and answer: if isinstance(answer, datetime): return answer try: dt = dateutil.parser.parse(answer) if is_naive(dt): dt = make_aware( dt, pytz.timezone(self.event.settings.timezone)) return dt except: raise ValidationError(_('Invalid datetime input.')) return answer
def to_python(self, value): """ Returns the result range of float. Returns None for empty values. """ value = super(RangeField, self).to_python(value) for x in value: if not x in validators.EMPTY_VALUES: break else: return None n = len(value) if self.localize: for i in range(n): value[i] = formats.sanitize_separators(value[i]) error_messages = (self.error_messages['invalid_start'], self.error_messages['invalid_end']) for i in range(n): try: value[i] = float(value[i]) except (ValueError, TypeError): raise ValidationError(error_messages[i]) if value[0] > value[1]: raise ValidationError(self.error_messages['invalid_range']) if not self.min_value is None and self.min_value > value[0]: raise ValidationError(self.error_messages['min_range_value'] % {'limit_value': self.min_value}) if not self.max_value is None and self.max_value < value[1]: raise ValidationError(self.error_messages['max_range_value'] % {'limit_value': self.max_value}) #logger.debug("\n\n\n\n\n to_python: %s \n\n\n\n\n" % value) return value
def post(self, request, slug): add_info = "" if request.user.is_anonymous: return redirect('account_login') else: if request.POST.get('hinta-2'): price = sanitize_separators(request.POST.get('hinta-2')) amount = sanitize_separators(request.POST.get('amount-2')) gluteen = False laktoos = False add_info = sanitize_separators(request.POST.get('lisaa-2')) else: price = sanitize_separators(request.POST.get('price')) amount = sanitize_separators(request.POST.get('amount')) gluteen = sanitize_separators(request.POST.get('gluteen')) laktoos = sanitize_separators(request.POST.get('laktoos')) add_info = sanitize_separators(request.POST.get('lisaa')) if gluteen: price = str(float(price) + 5.00) if laktoos: price = str(float(price) + 5.00) product = get_object_or_404(Product, slug=slug) try: order_qs = OrderItem.objects.get( user=self.request.user, ordered=False, product=product, price=price, is_gluteen_free=isinstance(gluteen, str), is_loctose_free=isinstance(laktoos, str), additional_info=add_info, ) order_qs.quantity += int(amount) if gluteen: order_qs.is_gluteen_free = True if laktoos: order_qs.is_loctose_free = True order_qs.save() messages.info(self.request, "Tämä tuote lisättiin ostoskoriin") return redirect("main:product", slug=slug) except OrderItem.DoesNotExist: OrderItem.objects.create( product=product, user=request.user, ordered=False, price=price, quantity=amount, is_gluteen_free=isinstance(gluteen, str), is_loctose_free=isinstance(laktoos, str), additional_info=add_info, ) messages.info(self.request, "Tämä tuote lisättiin ostoskoriin") return redirect("main:product", slug=slug) except: HttpResponseBadRequest()
def clean(self, value, previous_values): if value not in (None, ''): value = formats.sanitize_separators(re.sub(r'[^0-9.,-]', '', value)) try: value = Decimal(value) except (DecimalException, TypeError): raise ValidationError(_('You entered an invalid number.')) return value
def clean_answer(self, answer): if self.required: if not answer or (self.type == Question.TYPE_BOOLEAN and answer not in ("true", "True", True)): raise ValidationError(_('An answer to this question is required to proceed.')) if not answer: if self.type == Question.TYPE_BOOLEAN: return False return None if self.type == Question.TYPE_CHOICE: try: return self.options.get(pk=answer) except: raise ValidationError(_('Invalid option selected.')) elif self.type == Question.TYPE_CHOICE_MULTIPLE: try: if isinstance(answer, str): return list(self.options.filter(pk__in=answer.split(","))) else: return list(self.options.filter(pk__in=answer)) except: raise ValidationError(_('Invalid option selected.')) elif self.type == Question.TYPE_BOOLEAN: return answer in ('true', 'True', True) elif self.type == Question.TYPE_NUMBER: answer = formats.sanitize_separators(answer) answer = str(answer).strip() try: return Decimal(answer) except DecimalException: raise ValidationError(_('Invalid number input.')) elif self.type == Question.TYPE_DATE: if isinstance(answer, date): return answer try: return dateutil.parser.parse(answer).date() except: raise ValidationError(_('Invalid date input.')) elif self.type == Question.TYPE_TIME: if isinstance(answer, time): return answer try: return dateutil.parser.parse(answer).time() except: raise ValidationError(_('Invalid time input.')) elif self.type == Question.TYPE_DATETIME and answer: if isinstance(answer, datetime): return answer try: dt = dateutil.parser.parse(answer) if is_naive(dt): dt = make_aware(dt, pytz.timezone(self.event.settings.timezone)) return dt except: raise ValidationError(_('Invalid datetime input.')) return answer
def get_parsed_value(self, value): if value is not None and isinstance(value, basestring): value = formats.sanitize_separators(value) try: return float(value) except ValueError: # return value if any error happends that will get validated pass return value
def save(self, commit=True): job = self.instance if self.cleaned_data["status_complete"]: job.complete() for task in job.all_tasks.all(): if task.is_time_and_materials: for li in task.lineitems.all(): expended_local = self.data["li-{}-complete".format(li.id)] expended_canonical = formats.sanitize_separators( expended_local) new_expended = Decimal(expended_canonical.strip()) if li.expended != new_expended: li.expended = new_expended li.save() ExpendReport.objects.create( worker=Worker.objects.get( pk=self.data["li-{}-worker".format(li.id)]), lineitem=li, expended=li.expended, comment=self.data["li-{}-comment".format(li.id)] or self.cleaned_data["comment"], ) else: complete_local = self.data["task-{}-complete".format(task.id)] complete_canonical = formats.sanitize_separators( complete_local) new_complete = Decimal(complete_canonical.strip()) if task.complete != new_complete: task.complete = new_complete task.save() ProgressReport.objects.create( worker=Worker.objects.get( pk=self.data["task-{}-worker".format(task.id)]), task=task, complete=task.complete, comment=self.data["task-{}-comment".format(task.id)] or self.cleaned_data["comment"], ) return super().save(commit)
def to_python(self, value): if value in validators.EMPTY_VALUES: return None if self.localize: value = formats.sanitize_separators(value) value = smart_str(value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid']) return self.conversion(value, self.units, DATABASE_UNITS)
def to_python(self, value): if value in validators.EMPTY_VALUES: return None if self.localize: value = formats.sanitize_separators(value) value = smart_str(value).strip() value = value.replace(',', '.') try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid']) return value
def to_python(self, value): if value in validators.EMPTY_VALUES: return None if self.localize: value = formats.sanitize_separators(value) value = re.sub(r'\s|\tr', '', value) value = smart_text(value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid']) return value
def savedata(content, user): print(content) dict_creat = content.dict() dict_creat.pop('csrfmiddlewaretoken', None) dict_creat.pop('data', None) x = dict_creat.keys() id_equipment = list() for y in x: s = str(y) z = s.split("-") id_equipment.append(z[0]) unik_id = sorted(list(set(id_equipment))) print(unik_id) for i in unik_id: MyData = Measurements() MyData.equipment = Equipment.objects.get( equipment_name=dict_creat.get(str(i) + "-" + 'equipment_name')) MyData.weight = sanitize_separators( dict_creat.get(str(i) + "-" + 'weight_value')) MyData.size_one = sanitize_separators( dict_creat.get(str(i) + "-" + 'size_one_value')) MyData.size_two = sanitize_separators( dict_creat.get(str(i) + "-" + 'size_two_value')) MyData.airPD = sanitize_separators( dict_creat.get(str(i) + "-" + 'airPd_value')) MyData.airVent = sanitize_separators( dict_creat.get(str(i) + "-" + 'airVent_value')) MyData.data_messure = now() MyData.time_messure = now() MyData.name_user = user comparision(MyData) MyData.save()
class Activity(models.Model): outcome_entries = [ ('Outcome1', 'Outcome 1'), ('Outcome2', 'Outcome 2'), ('Outcome3', 'Outcome 3'), ('Outcome4', 'Outcome 4'), ] outcome = models.CharField(max_length=8, choices=outcome_entries, default='') total_budget = models.FloatField(max_length=100, default="", editable=True, help_text="Please enter the total " "budget for your outcome") sanitize_separators(total_budget) # outcome = models.ForeignKey('Outcome', max_length=8, on_delete=models.CASCADE, default="", editable=True) activity = models.CharField(max_length=500, help_text="Please Enter the activity you are reporting for") sub_activity = models.CharField(max_length=500, help_text="Please Enter the sub_activity of the above activity") cost = models.FloatField(max_length=500, help_text="Enter the cost of the gender activity") sanitize_separators(cost) description = models.TextField(max_length=500, help_text="Tell us more here") # total_budget = formats.sanitize_separators(total_budget) # cost = formats.sanitize_separators(cost) def display_outcome(self): """Create a string for the Outcome.""" return ', '.join(outcome.name for outcome in self.outcome.all()) display_outcome.short_description = 'Outcome' def __str__(self): """String for representing the Model object.""" return self.activity def get_absolute_url(self): """Returns the url to access a detail record for this activity.""" return reverse('activity_detail', args=[str(self.id)])
def to_python(self, value): """ Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in validators.EMPTY_VALUES: return None value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"]) return value
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(Html5IntegerField, self).to_python(value) if value in validators.EMPTY_VALUES: return None if self.localize: value = formats.sanitize_separators(value) try: value = int(str(value)) except (ValueError, TypeError): raise exceptions.ValidationError(self.error_messages['invalid']) return value
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in validators.EMPTY_VALUES: return None if self.localize: value = formats.sanitize_separators(value) try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) return value
def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def to_python(self, value): """ Validate that int() can be called on the input. Return the result of int() or None for empty values. """ value = super().to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub('', str(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub('', str(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def to_python(self, value): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ if value in validators.EMPTY_VALUES: return None value = formats.sanitize_separators(value) value = smart_str(value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages["invalid"]) return value
def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = Decimal(str(value)) except DecimalException: raise ValidationError(self.error_messages["invalid"], code="invalid") return value
def to_python(self, value): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) value = smart_text(value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) value = force_text(value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def to_python(self, value): if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) value = smart_text(value).strip() if "/" in value: numerator, denominator = value.split("/", 2) tp = super(DivideDecimalField, self).to_python value = tp(numerator) / tp(denominator) if value: # In Python 3, a simple round() call is enough. To support # Python 2, we have to do this quantize thing. quantize_target = ".".join(["1", "0" * self.decimal_places]) return value.quantize(Decimal(quantize_target)) else: return super(DivideDecimalField, self).to_python(value)
def post(self, request): data = {} data['form_item'] = ItemPedidoForm() data['numero'] = int(request.POST['numero']) data['desconto'] = sanitize_separators(request.POST['desconto']) data['venda_id'] = request.POST['venda_id'] if data['venda_id']: venda = Venda.objects.get(id=data['venda_id']) venda.desconto = data['desconto'] venda.numero = data['numero'] venda.save() else: venda = Venda.objects.create(numero=data['numero'], desconto=data['desconto']) itens = venda.itempedido_set.all() data['venda'] = venda data['itens'] = itens return render(request, 'vendas/novo-pedido.html', data)
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Validate if yyyymm format or not. if not re.match(r'^\d{6}$', value): raise ValidationError(self.error_messages['invalid'], code='invalid') # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub('', force_text(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid'], code='invalid') return value
def get_queryset(self): """Filter the default query set.""" qs = super(QueryFilterMixin, self).get_queryset() kw = '{0}__{1}'.format( self.filter_attr, 'icontains' if self.filter_ignore_case else 'contains') if self.filter_num_attr is not None: okw = '{0}__{1}'.format(self.filter_num_attr, 'exact') for f in self.get_filter_keywords(): dct, n = {}, None if self.filter_num_attr is not None: try: n = float(formats.sanitize_separators(f)) dct[okw] = n except ValueError: pass if n is None: dct[kw] = f qs = qs.filter(**dct) return qs
def to_python(self, value): value = super(BBoxField, self).to_python(value) if not value: return -180.0,-90.0,180.0,90.0 try: lx, ly, ux, uy = value.split(',') if self.localize: lx = float(sanitize_separators(lx)) ly = float(sanitize_separators(ly)) ux = float(sanitize_separators(ux)) uy = float(sanitize_separators(uy)) if uy < ly or ux < lx: raise ValidationError("BBoxes must be in lower-left(x,y), upper-right(x,y) order") except (ValueError, TypeError): raise ValidationError("BBoxes must be four floating point values separated by commas") lx = float(sanitize_separators(lx)) ly = float(sanitize_separators(ly)) ux = float(sanitize_separators(ux)) uy = float(sanitize_separators(uy)) return lx, ly, ux, uy
"""
def parse_decimal_value(value: str) -> Decimal: if not isinstance(value, str): raise InvalidOperation("Decimal must be a string") return Decimal(sanitize_separators(value))