def money_filter(value: Decimal, arg='', hide_currency=False): if isinstance(value, float) or isinstance(value, int): value = Decimal(value) if not isinstance(value, Decimal): raise TypeError("Invalid data type passed to money filter: %r" % type(value)) if not arg: raise ValueError("No currency passed.") arg = arg.upper() places = settings.CURRENCY_PLACES.get(arg, 2) rounded = value.quantize(Decimal('1') / 10 ** places, ROUND_HALF_UP) if places < 2 and rounded != value: places = 2 if hide_currency: return floatformat(value, places) try: if rounded != value: # We display decimal places even if we shouldn't for this currency if rounding # would make the numbers incorrect. If this branch executes, it's likely a bug in # pretix, but we won't show wrong numbers! return '{} {}'.format( arg, floatformat(value, 2) ) return format_currency(value, arg, locale=translation.get_language()) except: return '{} {}'.format( arg, floatformat(value, places) )
def money_filter(value: Decimal, arg='', hide_currency=False): if isinstance(value, float) or isinstance(value, int): value = Decimal(value) if not isinstance(value, Decimal): raise TypeError("Invalid data type passed to money filter: %r" % type(value)) if not arg: raise ValueError("No currency passed.") places = settings.CURRENCY_PLACES.get(arg, 2) rounded = value.quantize(Decimal('1') / 10 ** places, ROUND_HALF_UP) if places < 2 and rounded != value: places = 2 if hide_currency: return floatformat(value, places) try: if rounded != value: # We display decimal places even if we shouldn't for this currency if rounding # would make the numbers incorrect. If this branch executes, it's likely a bug in # pretix, but we won't show wrong numbers! return '{} {}'.format( arg, floatformat(value, 2) ) return format_currency(value, arg, locale=translation.get_language()) except: return '{} {}'.format( arg, floatformat(value, places) )
class ProjectDetailsTable(tables.Table): invoice_id = tables.Column(orderable=False, verbose_name="") date = tables.Column(order_by=("date"), attrs={"td": {"class": "nowrap-column"}}) incurred_hours = tables.Column(footer=lambda table: "{}h".format(intcomma(floatformat(sum(x.incurred_hours for x in table.data), 0)))) incurred_money = tables.Column(footer=lambda table: "{}€".format(intcomma(floatformat(sum(x.incurred_money for x in table.data), 0)))) bill_rate_avg = tables.Column(footer=lambda table: "{:.0f}€/h".format(calc_bill_rate_avg((x.incurred_hours, x.incurred_money) for x in table.data))) incorrect_entries_count = tables.Column(footer=lambda table: sum(x.incorrect_entries_count for x in table.data)) class Meta: model = Invoice attrs = {"class": "table table-striped table-hover invoice-table table-responsive"} fields = ("date", "invoice_state", "has_comments", "incorrect_entries_count", "incurred_hours", "bill_rate_avg", "incurred_money", "billable_percentage", "invoice_id") template_name = "django_tables2/bootstrap4.html" def render_date(self, value): return format_html(f"{value:%Y-%m}") def render_invoice_id(self, value): return format_html("<a href='{}'>Invoice</a>, <a href='{}'>hours</a>".format(reverse("invoice", args=[value]), reverse("invoice_hours", args=[value]))) def render_bill_rate_avg(self, value): return "{}€/h".format(intcomma(floatformat(value, 0))) def render_incurred_hours(self, value): return "{}h".format(intcomma(floatformat(value, 0))) def render_incurred_money(self, value): return "{}€".format(intcomma(floatformat(value, 0))) def render_billable_percentage(self, value): return "{}%".format(floatformat(value * 100, 0))
class ProjectsTable(tables.Table): starts_at = tables.Column(order_by=("starts_at"), attrs={"td": {"class": "nowrap-column"}}) ends_at = tables.Column(order_by=("ends_at"), attrs={"td": {"class": "nowrap-column"}}) client_m = tables.Column(order_by=("client_m"), verbose_name="Client") incurred_hours = tables.Column(footer=lambda table: "{}h".format(intcomma(floatformat(sum(x.incurred_hours for x in table.data), 0)))) incurred_money = tables.Column(footer=lambda table: "{}€".format(intcomma(floatformat(sum(x.incurred_money for x in table.data), 0)))) class Meta: model = Project attrs = {"class": "table table-striped table-hover projects-table table-responsive"} fields = ("client_m", "name", "admin_users", "starts_at", "ends_at", "incurred_hours", "incurred_money") template_name = "django_tables2/bootstrap4.html" def render_client_m(self, value, record): return format_html("<a href='{}'>{}</a>".format(reverse("client_details", args=(record.client_m.id,)), value)) def render_name(self, value, record): return format_html("<a href='{}'>{}</a>".format(reverse("project", args=[record.guid]), value)) def render_incurred_hours(self, value): return "{}h".format(intcomma(floatformat(value, 0))) def render_incurred_money(self, value): return "{}€".format(intcomma(floatformat(value, 0))) def render_admin_users(self, value): return format_html(" ".join(["<a class='badge badge-secondary' href='{}'>{} {}</a>".format(reverse("person_overview", args=(a.guid,)), a.first_name, a.last_name) for a in value.all()])) def render_guid(self, value): return format_html("<a href='{}'>Details</a>".format(reverse("project", args=[value])))
def __unicode__(self): if self.output and self.input: return u'{}: {} (-{}/+{})'.format(self.date, self.text, intcomma(floatformat(self.output, 2)), intcomma(floatformat(self.input, 2))) elif self.output: return u'{}: {} (-{})'.format(self.date, self.text, intcomma(floatformat(self.output, 2))) else: return u'{}: {} (+{})'.format(self.date, self.text, intcomma(floatformat(self.input, 2)))
class GlobalUsageTable(BaseUsageTable): project = tables.Column('project_name', verbose_name=_("Project Name")) vcpu_hours = tables.Column('vcpu_hours', verbose_name=_("VCPU Hours"), help_text=_("Total VCPU usage (Number of " "VCPU in instance * Hours Used) " "for the project"), filters=(lambda v: floatformat(v, 2), )) disk_hours = tables.Column('disk_gb_hours', verbose_name=_("Disk GB Hours"), help_text=_("Total disk usage (GB * " "Hours Used) for the project"), filters=(lambda v: floatformat(v, 2), )) memory_hours = tables.Column('memory_mb_hours', verbose_name=_("Memory MB Hours"), help_text=_("Total memory usage (MB * " "Hours Used) for the project"), filters=(lambda v: floatformat(v, 2), )) def get_object_id(self, datum): return datum.tenant_id class Meta(object): name = "global_usage" hidden_title = False verbose_name = _("Usage") columns = ("project", "vcpus", "disk", "memory", "vcpu_hours", "disk_hours", "memory_hours") table_actions = (CSVSummary, ) multi_select = False
def display_user_problem(self, participation, contest_problem): format_data = (participation.format_data or {}).get(str(contest_problem.id)) if format_data: penalty = format_html( '<small style="color:red"> ({penalty})</small>', penalty=floatformat( format_data['penalty'])) if format_data['penalty'] else '' return format_html( '<td class="{state}"><a href="{url}">{points}{penalty}<div class="solving-time">{time}</div></a></td>', state=(('pretest-' if self.contest.run_pretests_only and contest_problem.is_pretested else '') + self.best_solution_state(format_data['points'], contest_problem.points)), url=reverse('contest_user_submissions', args=[ self.contest.key, participation.user.user.username, contest_problem.problem.code ]), points=floatformat(format_data['points']), penalty=penalty, time=nice_repr(timedelta(seconds=format_data['time']), 'noday'), ) else: return mark_safe('<td></td>')
def get_current_sum_display(self): if self.current_sum < 0: return '<span class="txt-color-green">{}</span>'.format(intcomma(floatformat(-self.current_sum, 2))) elif self.current_sum > 0: return '<span class="txt-color-red">{}</span>'.format(intcomma(floatformat(-self.current_sum, 2))) else: return '0.00'
def handle(self, *args, **options): """ Update periodic update events and send notifications for upcoming update events. """ # command to run: python manage.py tunga_export_payments participant_payments = ParticipantPayment.objects.filter(participant__task__paid=True) print('participant_payments', len(participant_payments)) with open('developer_payments.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow([ 'Task', 'Fee', 'Developer', 'Dev BTC Address', 'BTC Sent', 'Task BTC Address', 'Invoice Date', 'Paid By', 'URL', 'Developer Invoice', 'Client Invoice' ]) for payment in participant_payments: row = [ payment.participant.task.summary, 'EUR {}'.format(floatformat(payment.participant.task.fee, -2)), payment.participant.user.display_name, payment.destination, 'BTC {}'.format(floatformat(payment.btc_sent, -6)), payment.participant.task.btc_address, payment.participant.task.taskinvoice_set.first().created_at.strftime("%d %b, %Y"), payment.participant.task.user.display_name, '{}/work/{}'.format(TUNGA_URL, payment.participant.task.id), '{}/api/task/{}/download/invoice/?format=pdf&type=developer'.format(TUNGA_URL, payment.participant.task.id), '{}/api/task/{}/download/invoice/?format=pdf&type=client'.format(TUNGA_URL, payment.participant.task.id) ] spamwriter.writerow(row)
def test_zero_values(self): self.assertEqual(floatformat(0, 6), "0.000000") self.assertEqual(floatformat(0, 7), "0.0000000") self.assertEqual(floatformat(0, 10), "0.0000000000") self.assertEqual( floatformat(0.000000000000000000015, 20), "0.00000000000000000002" )
def get_price_display(self): if self.payment_parameters is None: return None base_price = self.payment_parameters.get("price", 0) min_price = base_price max_price = base_price for mapping in self.payment_parameters.get("mappings", []): prices = [m["price"] for m in mapping["mapping"]] min_price += min(prices) max_price += max(prices) if min_price == max_price == 0: if "free_pricing" in self.payment_parameters: return "Prix libre" else: return None if min_price == max_price: display = "{} €".format(floatformat(min_price / 100, 2)) else: display = "de {} à {} €".format( floatformat(min_price / 100, 2), floatformat(max_price / 100, 2) ) if "free_pricing" in self.payment_parameters: display += " + montant libre" return display
def test_get_context_data(self): membership = Membership(pk=2, type=Membership.MEMBER) self.view.request = MagicMock() with mock.patch("members.models.Membership.objects") as _qs: Membership.objects.filter().exists.return_value = True context = self.view.get_context_data(form=MagicMock()) self.assertEqual(len(context), 7) self.assertEqual( context["year_fees"], floatformat(settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2), ) self.assertEqual( context["study_fees"], floatformat(settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2), ) self.assertEqual(context["was_member"], True) Membership.objects.filter().exists.return_value = False context = self.view.get_context_data(form=MagicMock()) self.assertEqual(context["was_member"], False) with self.subTest("With latest membership"): self.view.request.member.latest_membership = membership context = self.view.get_context_data(form=MagicMock()) self.assertEqual(context["latest_membership"], membership) with self.subTest("Without latest membership"): self.view.request.member.latest_membership = None context = self.view.get_context_data(form=MagicMock()) self.assertEqual(context["latest_membership"], None)
def instance_consumption(self): sample_data = [] resource_rates = self.get_resource_rates() query = [{'field' : 'metadata.event_type', 'value' : None }] query += self.additional_query() sample = self.get_sample('instance', query) for s in sample: stat = self.get_stats(s.counter_name, s.resource_id) rates = {} for k, v in s.resource_metadata.items(): key = re.sub('[.]', '_', k) duration = float(stat[0].duration) // 3600 if resource_rates.filter(type=k): rate_type = resource_rates.filter(type=k) rate_value = float(rate_type[0].rate) * float(v) rates[key] = rate_value * duration s.instance_name = s.resource_metadata['display_name'] s.flavor_ram = "$ %s" % floatformat(rates['flavor_ram'], 2) s.flavor_vcpus = "$ %s" % floatformat(rates['flavor_vcpus'], 2) s.root_gb = "$ %s" % floatformat(rates['root_gb'], 2) s.instance_uptime = datetime.timedelta(seconds=stat[0].duration) s.server_start = parse(stat[0].duration_start) s.server_update = parse(stat[0].duration_end) s.instance_price_value = 0 for k, v in rates.items(): s.instance_price_value += float(v) s.instance_price_value = "$ %s" % floatformat(s.instance_price_value, 2) sample_data.append(s) return sample_data
def invoice_detail(request, invoice_id, template_name='invoice_detail.html'): invoice = Invoice.objects.get(pk=invoice_id) items = Item.objects.filter(invoice=invoice) client = invoice.client emission_date = invoice.emission_date invoice_total_value = 0 precision = 2 for item in items: invoice_total_value += item.value item.value = floatformat(item.value, precision) item.value, decimal = force_unicode(item.value).split('.') item.value = intcomma(item.value) item.value = item.value.replace(',', '.') + ',' + decimal invoice_total_value = floatformat(invoice_total_value, precision) invoice_total_value, decimal = force_unicode(invoice_total_value)\ .split('.') invoice_total_value = intcomma(invoice_total_value) invoice_total_value = invoice_total_value.replace(',', '.') + ',' + decimal context = { 'invoice_total_value': invoice_total_value, 'invoice': invoice, 'items': items, 'client': client, 'emission_date': emission_date, } return render(request, template_name, context)
def get_description_deals(user, obj): order_id = obj.pk if not user == obj.user: if obj.el.sale.user == user: order_id = obj.el.sale.pk if obj.el.buy.user == user: order_id = obj.el.buy.pk if obj.w_action(user) == 'sale': return u"Продажа {w_amo_sum_total} {left} с вашего ордера #{pk} по цене {rate} {right} всего {w_total_total} {right} (-{commission}%)".format(**{ "w_amo_sum_total": floatformat(obj.el._part_amo_sum, -8), "left": obj.el.pair.left, "pk": order_id, "rate": floatformat(obj.profitable.rate, -8), "right": obj.el.pair.right, "w_total_total": floatformat(obj.el._part_amo_sum * obj.el._rate, -8), #"w_total_total": floatformat(obj.el._part_amo_sum * obj.el._rate * (1 - obj.commission / D(100)), -8), "commission": obj.commission, }) if obj.w_action(user) == 'buy': return u"Покупка {w_amo_sum_total} {left} (-{commission}%) с вашего ордера #{pk} по цене {rate} {right}".format(**{ "w_amo_sum_total": floatformat(obj.el._part_amo_sum, -8), #"w_amo_sum_total": floatformat(obj.el._part_amo_sum * (1 - obj.commission / D(100)), -8), "left": obj.el.pair.left, "pk": order_id, "rate": floatformat(obj.profitable.rate, -8), "right": obj.el.pair.right, "commission": obj.commission, })
def intword(value): """ Converts a large integer to a friendly text representation. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 millions' and '1200000000' becomes '1.2 billions'. """ try: value = float(value) except TypeError: # value is None value = 0 except ValueError: # not translated to number return value value /= 100. # prices are in cents, we translate them to euros. for exponent, converter in intword_converters: large_number = 10 ** exponent if value < large_number * 1000: new_value = value / large_number new_value = defaultfilters.floatformat(new_value, 1) return converter(new_value) % {'value': new_value} # use the highest available exponent, converter = intword_converters[-1] large_number = 10 ** exponent new_value = value / float(large_number) new_value = defaultfilters.floatformat(new_value, 1) return converter(new_value) % {'value': new_value}
def order(request, form): dajax = Dajax() q = deserialize_form(form) ttype = '' if not q.get('buy-amount', None) is None: ttype = 'buy' if not q.get('sale-amount', None) is None: ttype = 'sale' form = OrdersForm(prefix=ttype, data=q) if form.is_valid(): c = form.cleaned_data user = request.user if user.is_authenticated() and user.is_active: pair, amount, rate = c.get('pair'), c.get('amount'), c.get('rate') total, commission, pos = pair.calc(amount, rate, ttype) if ttype == 'buy': pos = pair.right if ttype == 'sale': pos = pair.left valuta = pos.value balance = user.orders_balance(valuta) if ttype == 'buy': _sum = balance - total if ttype == 'sale': _sum = balance - amount if _sum >= 0: _ret = getattr(pair, "order_%s" % ttype)(user, amount, rate) dajax.remove_css_class( '#{type}_form input'.format(**{"type": ttype}), 'error') dajax.script("location.reload();") else: text = "Сумма сделки превышает ваш баланс на {sum} {valuta}".format( **{ "sum": floatformat(-_sum, -8), "valuta": pos }) dajax.script( "$('#info_{type}').text('{text}');".format(**{ "type": ttype, "text": text, })) else: pair, amount, rate = c.get('pair'), c.get('amount'), c.get('rate') total, commission, pos = pair.calc(amount, rate, ttype) if ttype == 'buy': _sum = total if ttype == 'sale': _sum = amount text = "Сумма сделки превышает ваш баланс на {sum} {valuta}".format( **{ "sum": floatformat(-_sum, -8), "valuta": pos }) dajax.script( "$('#info_{type}').text('{text}');".format(**{ "type": ttype, "text": text, })) else: dajax.script("$('#info_{type}').text('{text}');".format( **{ "type": ttype, "text": "Неправильно заполнено одно из полей.", })) for error in form.errors: dajax.add_css_class('#id_%s-%s' % (ttype, error), 'error') return dajax.json()
def trans_return(self): if self.is_action('sale'): return "%s %s" % (floatformat(self.el._part_amo_sum or self.amount, -8), self.pair.left) if self.is_action('buy'): return "%s %s" % (floatformat( self.el._part_amo_sum * self.el._rate or self.amount * self.rate, -8), self.pair.right)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["google_api_key"] = settings.GOOGLE_PLACES_API_KEY context["year_fees"] = floatformat( settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2) context["study_fees"] = floatformat( settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2) return context
def get_current_sum_display(self): if self.current_sum < 0: return '<span class="txt-color-green">{}</span>'.format( intcomma(floatformat(-self.current_sum, 2))) elif self.current_sum > 0: return '<span class="txt-color-red">{}</span>'.format( intcomma(floatformat(-self.current_sum, 2))) else: return '0.00'
def test_zero_values(self): """ Check that we're not converting to scientific notation. """ self.assertEqual(floatformat(0, 6), '0.000000') self.assertEqual(floatformat(0, 7), '0.0000000') self.assertEqual(floatformat(0, 10), '0.0000000000') self.assertEqual(floatformat(0.000000000000000000015, 20), '0.00000000000000000002')
def balances(self): total = self.total_charges() diff = self.amount - total if self.amount == total: return "Exact" elif diff > 0: return "$%s short" % str(intcomma(floatformat(diff, 2))) else: return "$%s over" % str(intcomma(floatformat(-1 * diff, 2)))
def test_infinity(self): pos_inf = float(1e30000) self.assertEqual(floatformat(pos_inf), six.text_type(pos_inf)) neg_inf = float(-1e30000) self.assertEqual(floatformat(neg_inf), six.text_type(neg_inf)) nan = pos_inf / pos_inf self.assertEqual(floatformat(nan), six.text_type(nan))
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["year_fees"] = floatformat( settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2 ) context["study_fees"] = floatformat( settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2 ) return context
def price_range(tickets): current_tickets = tickets.exclude(offered_from__gt=date.today(), offered_to__lt=date.today()) current_tickets = current_tickets.exclude(available=0) min_ticket = current_tickets.aggregate(Min('price'))['price__min'] max_ticket = current_tickets.aggregate(Max('price'))['price__max'] if min_ticket == max_ticket: return defaultfilters.floatformat(min_ticket) else: return '%s - %s' % (defaultfilters.floatformat(min_ticket), defaultfilters.floatformat(max_ticket))
def prefdist(val, arg): """ Example: {{v.profile.get_distance|prefdist:user}} :val: distance in meters :arg: User instance who's pref_distance_unit setting to use """ if arg.profile.pref_distance_unit == 'km': return '{} km'.format(floatformat(meters_in_km(val), 1)) elif arg.profile.pref_distance_unit == 'mi': return '{} miles'.format(floatformat(meters_in_miles(val), 1))
def test_get_context_data(self): context = self.view.get_context_data() self.assertEqual(len(context), 3) self.assertEqual( context["year_fees"], floatformat(settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2), ) self.assertEqual( context["study_fees"], floatformat(settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2), )
def __str__(self): if self.output and self.input: return u'{}: {} (-{}/+{})'.format( self.date, self.text, intcomma(floatformat(self.output, 2)), intcomma(floatformat(self.input, 2))) elif self.output: return u'{}: {} (-{})'.format( self.date, self.text, intcomma(floatformat(self.output, 2))) else: return u'{}: {} (+{})'.format(self.date, self.text, intcomma(floatformat(self.input, 2)))
def important_info(self, player, years, teams): return { 'player_name': player.player_name, 'overs': floatformat(player.get_overs(years, teams)), 'maidens': player.get_maidens(years, teams), 'runs': player.get_bowl_runs(years, teams), 'wickets': player.get_wickets(years, teams), 'average': floatformat(player.get_bowl_average(years, teams)), 'economy': floatformat(player.get_economy(years, teams)), 'wickets_5': player.get_5_wickets(years, teams), }
def _w(self, content): if content is not None: if isinstance(content, TaxlessPrice) or isinstance(content, TaxfulPrice): content = floatformat(content.amount.value, 2) if isinstance(content, Decimal): content = floatformat(content, 2) if isinstance(content, Promise): content = force_text(content) self.output.append(content)
def real_get(self): min = self.request.get("min") max = self.request.get("max") if min != "": self.data.set_min(min) self.data.put() return floatformat(self.data.min) if max != "": self.data.set_max(max) self.data.put() return floatformat(self.data.max) return 0
class UsageTable(tables.DataTable): date = tables.Column('date', verbose_name=_("Date")) top_io = tables.Column('top_io', verbose_name=_("IO(Mb/s)"), filters=(lambda v: floatformat(v, 2),)) total_flow = tables.Column('total_flow', verbose_name=_("Total Flow"), filters=(lambda v: floatformat(v, 2), sizeformat.mb_float_format)) def get_object_id(self, datum): return datum.date class Meta(object): name = "usage" verbose_name = _("Usage")
def find_weather_stations(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): location = urllib.quote_plus(form.cleaned_data['location']) request_url = "http://maps.google.com/maps/geo?q=%s&output=%s&key=%s" % (location, "csv", settings.GOOGLE_MAPS_API_KEY) data = urllib.urlopen(request_url).read() dlist = data.split(',') if dlist[0] == '200': point = Point((float(dlist[3]), float(dlist[2])),) else: point = None markers = [] if point: marker = GMarker(point, request.POST['location']) marker.add_event(GEvent('click', 'function() { geodjango.map_marker1.openInfoWindowHtml("%s") }' % form.cleaned_data['location'])) # the gis.maps.google.* stuff doesn't allow for ^^^^^ dynamic naming of these - with multiple points, it will be # necessary to for loop through the points with your own counter (start from zero) and that should coincide with # the template forloop counter being used - but by all means cross-check that every time to make sure it's right. markers.append(marker) weather_stations = find_nearest_weather_stations(point, qty=10) count = 2 for station in weather_stations: marker = GMarker(station.point, '%s %s' % (station.code, station.get_name())) marker.add_event(GEvent('click', 'function() { geodjango.map_marker%s.openInfoWindowHtml("%s"); }' % \ (count, "%s, (altitude %s ft.) - %s mi @ %s deg""" \ % (station.code, floatformat(m_to_ft(station.elevation), 0), floatformat(station.distance.mi, 2), floatformat(rad_to_deg(station.azimuth)))) )) markers.append(marker) count = count + 1 map = GoogleMap(key=settings.GOOGLE_MAPS_API_KEY, markers=markers) return render_to_response('locationfinder.html', { 'location': form.cleaned_data['location'], 'location_point': point, 'google': map, 'weather_stations': weather_stations, }) else: return render_to_response('locationfinder.html', { 'location': location, }) else: return render_to_response('locationfinder.html', {'form': form,}) else: form = SearchForm() return render_to_response('locationfinder.html', {'form': form,})
def get(self, request, codename): try: package = Package.objects.get(codename=codename) except (Package.DoesNotExist, AttributeError, ValueError): return JsonResponse(data=None, status=400, safe=False) data = { "duration": package.days, "roi": package.return_on_investmentent, "minimum_amount": intcomma(floatformat(package.minimum_amount)), "maximum_amount": intcomma(floatformat(package.maximum_amount)), } return JsonResponse(data=data, status=200, safe=False)
def test_unlocalize(self): with translation.override('de', deactivate=True): self.assertEqual(floatformat(66666.666, '2'), '66666,67') self.assertEqual(floatformat(66666.666, '2u'), '66666.67') with self.settings( USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=3, THOUSAND_SEPARATOR='!', ): self.assertEqual(floatformat(66666.666, '2gu'), '66!666.67') self.assertEqual(floatformat(66666.666, '2ug'), '66!666.67') # Invalid suffix. self.assertEqual(floatformat(66666.666, 'u2'), '66666.666')
def test_unlocalize(self): with translation.override("de", deactivate=True): self.assertEqual(floatformat(66666.666, "2"), "66666,67") self.assertEqual(floatformat(66666.666, "2u"), "66666.67") with self.settings( USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=3, THOUSAND_SEPARATOR="!", ): self.assertEqual(floatformat(66666.666, "2gu"), "66!666.67") self.assertEqual(floatformat(66666.666, "2ug"), "66!666.67") # Invalid suffix. self.assertEqual(floatformat(66666.666, "u2"), "66666.666")
def test_get_context_data(self): self.view.request = self.rf.post("/") context = self.view.get_context_data() self.assertEqual(len(context), 5) self.assertEqual( context["year_fees"], floatformat(settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2), ) self.assertEqual( context["study_fees"], floatformat(settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2), ) self.assertEqual(context["google_api_key"], "hello")
def valeur(self): retour = {} tarif = TarifFioul.objects.get(zone=self.zone, type_fioul=self.type_fioul) decote = TarifDecote.objects.get(zone=self.zone, min__lte=self.qte, max__gte=self.qte) livraison = TarifLivraison.objects.get( zone=self.zone, type_livraison=self.type_livraison) config = Config.objects.filter(actif=True)[0] retour["total_ttc"] = ( (tarif.prix_ttc + decote.decote + livraison.extra) * Decimal(self.qte) / Decimal(1000)) retour["prix_litre"] = retour["total_ttc"] / Decimal(self.qte) # retour['total_ttc'] += livraison.extra retour["total_ht"] = retour["total_ttc"] / (Decimal("1") + config.taux_tva) retour["livraison_ttc"] = livraison.extra retour["livraison_nom"] = livraison.type_livraison.nom retour["livraison_date"] = template_date(livraison.date_livraison(), "l j F") retour["livraisons"] = {} liv_prix_base = livraison.extra * Decimal(self.qte) / Decimal(1000) for liv in TarifLivraison.objects.filter(zone=self.zone, actif=True): liv_label = "" if self.type_livraison != liv.type_livraison: liv_prix = (liv.extra * Decimal(self.qte) / Decimal(1000)) - liv_prix_base if liv_prix > 0: liv_label = "+ " + localize(floatformat(liv_prix, "-2")) + " euros" elif liv_prix < 0: liv_label = ("- " + localize(floatformat(-1 * liv_prix, "-2")) + " euros") retour["livraisons"][liv.id] = liv_label retour["fioul_nom"] = tarif.type_fioul.nom retour["qte"] = int(self.qte) retour["acompte"] = config.commission * self.qte / 1000 retour["acompte_ht"] = retour["acompte"] / (1 + config.taux_tva) retour["reste"] = retour["total_ttc"] - retour["acompte"] retour["acompte"] = round(retour["acompte"], 2) retour["acompte_ht"] = round(retour["acompte_ht"], 2) retour["reste"] = round(retour["reste"], 2) retour["total_ttc"] = round(retour["total_ttc"], 2) retour["total_ht"] = round(retour["total_ht"], 2) retour["prix_litre"] = round(retour["prix_litre"], 4) retour["livraison_ttc"] = round(retour["livraison_ttc"], 2) return retour
def calc(self, amount, rate, ttype, totext=None): amount = D(amount) rate = D(rate) total = normalized(amount * rate, where="DOWN") if ttype == 'sale': _amo = total pos = self.right else: _amo = amount pos = self.left commission = normalized(_amo * self.commission / D(100)) if totext: return floatformat(total, -8), floatformat(commission, -8), pos return total, commission, pos
def calc_paymethod(request, value, paymethod, act="-"): dajax = Dajax() v = get_object_or_404(PaymentMethod, pk=paymethod, disable=False) calc_value = v.calc_commission(D(value)) calc_value1 = v.calc_commission(D(value), True) if act == "-": dajax.assign('#calc-value-result', 'value', floatformat(calc_value, -8).replace(",", ".")) else: dajax.assign('#balance-value', 'value', floatformat(calc_value1, -8).replace(",", ".")) dajax.assign('#calc-value-result', 'value', floatformat(value, -8).replace(",", ".")) return dajax.json()
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["year_fees"] = floatformat( settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_YEAR], 2 ) context["study_fees"] = floatformat( settings.MEMBERSHIP_PRICES[Entry.MEMBERSHIP_STUDY], 2 ) context["latest_membership"] = self.request.member.latest_membership context["was_member"] = Membership.objects.filter( user=self.request.member, type=Membership.MEMBER ).exists() context["benefactor_type"] = Membership.BENEFACTOR return context
def init_with_context(self, context): if self._initialized: return total = 0 results = [] for project in models.SalesReport.get_qs(): data = dict( pk=project.pk, code=project.code, title=project.short_name, ) if project.currency == storage.WALLET_CURRENCY_DOLLARS: value = project.price_full * project.exchange_rate else: value = project.price_full data['price'] = value total += value results.append(data) self.children = results[:SALES_LIMIT] self._initialized = True tpl = _(u'<div style="padding: 4px 8px; font-weight: bold;">Total amount is %s rub.</div>') self.pre_content = mark_safe(tpl % floatformat(total, 2))
def get_user_info(user, with_private=False): if user.facebook: info = { 'name': user.facebook.name, 'pic_url': '//graph.facebook.com/{}/picture'.format(user.facebook.uid), 'profile_url': '//facebook.com/{}/'.format(user.facebook.uid) } if with_private: info['auth'] = {'fb': {'uid': user.facebook.uid}} else: info = { 'name': user.guest_name(), 'pic_url': '//www.gravatar.com/avatar/{}.jpg?d=identicon'.format(hashlib.md5(user.id).hexdigest()), } # For now, score info is private if with_private: stats = { 'score': user.total_score, 'victories': user.games_won, 'elo': user.elo, } try: stats['win_ratio'] = floatformat((float(user.games_won) / user.games_finished) * 100.0) except ZeroDivisionError: pass info['stats'] = stats return info
def format_bid_string(self): if self.is_free(): return "Free" elif self.is_set_bid(): return "$"+ humanize.intcomma(defaultfilters.floatformat(self.cost, 2)) else: return "P"
def __init__(self, kpis, queryset=None, order_by=None, date=None, manual_date=False): """ kpis = kpi list queryset=registrations, order_by=kpi obj""" if not date: date = datetime.date.today() self.kpi = [] for kpitype in kpis: if isinstance(kpitype, (MonitorBoxKPI, MonitorTableKPI)): kpi = kpitype.kpi if not manual_date: if isinstance(kpitype, (MonitorBoxKPI, )) and kpitype.default_period == "WEEKLY": qs = queryset.filter(date__range=(DateInterval(date).week())) elif isinstance(kpitype, (MonitorBoxKPI, )) and kpitype.default_period == "MONTHLY": qs = queryset.filter(date__range=(DateInterval(date).month())) elif isinstance(kpitype, (MonitorBoxKPI, )) and kpitype.default_period == "YEARLY": qs = queryset.filter(date__range=(DateInterval(date).year())) else: qs = queryset.filter(date__day=date.day, date__month=date.month, date__year=date.year) else: qs = queryset else: kpi = kpitype qs = queryset data = self.calculate(kpi, qs) self.kpi.append({ 'id': kpitype.id, 'data': floatformat(data[0], kpi.decimal_places), 'data_u': data[0], # data unformatted 'subtitle_data': data[1], 'prefix': kpi.prefix, 'suffix': kpi.suffix, 'color': self.getColor(kpi, data[0]), 'title': kpi.title, }) if order_by == kpi: self.order_by = data
def percentage(value): if value is None: return None try: return floatformat(value * 100.0, 0) + '%' except: return None
def __init__(self, *args, **kwargs): from invoicing.models import InvoiceItem super(CreditNote, self).__init__(*args, **kwargs) if self.related_to and self.related_to.is_down_payment_invoice(): credit_note_data = self.current_revision if credit_note_data and self.id: description = _("%(percentage)s%% down-payment") if self.related_to.related_to: # Quotation | Purchase order (| Delivery order) if self.related_to.related_to.is_quotation(): description = _("%(percentage)s%% down-payment on quotation %(reference)s") elif self.related_to.related_to.is_purchase_order(): description = _("%(percentage)s%% down-payment on purchase order %(reference)s") credit_note_data.line_items.append( InvoiceItem( reference=self.related_to.ITEM_REFERENCE, description=description % { "percentage": floatformat(float(self.related_to.percentage * 100), -2), "reference": self.related_to.related_to.reference, }, quantity=1, unit_price=(self.amount / (Decimal("1.00") + self.related_to.tax_applied.rate)).quantize( Decimal("1.00"), ROUND_HALF_UP ), tax=self.related_to.tax_applied, ) )
def send_verify_email(email_address, verify_code): expiration_minute = floatformat(settings.EXPIRE_TIME / 60, 0) subject = u'注册验证码-来自云页网' from_email = settings.DEFAULT_FROM_EMAIL message_txt = u''' 尊敬的客户,您好! 感谢您注册云页网账号,您的注册码是:%s 。 此注册码有效期为 %s 分钟,超时需重新发送验证码。 武汉云页移动科技有限公司 联系电话:027-87345335 ''' % (verify_code, expiration_minute) email_message = EmailMultiAlternatives( subject, message_txt, from_email, [email_address] ) if getattr(settings, 'REGISTRATION_EMAIL_HTML', True): # todo:发送HTML格式的邮件,目前只支持纯文本 pass email_message.send()
def deccomma(amount, decimals=2): """ Humanize a number in the standard form -99,999.99 """ if not amount: return "" return intcomma(floatformat(amount, decimals))
def asmoney(amount): try: if isinstance(amount, str) or isinstance(amount, unicode): amount = float(amount) return u'¥%s%s' % (floatformat(amount, 2), u'元') except: return amount
def __getattr__(self, name): if name.endswith('_html'): _field = name.replace('_html', '_input') _label = _(self._meta.get_field(_field).verbose_name) _unit_field = name.replace('_html', '_unit') _val = floatformat(getattr(self, _field), 2) _method_name = u'get_%s_display' % _unit_field _unit_method = getattr(self, _method_name) return mark_safe(u'<div class="row-fluid">' \ '<div class="span6"><span class="readonly-label">%s:</span></div>' \ '<div class="span6"><strong class="readonly-value">%s %s</strong></div>' \ '</div>' % ( _label, _val, _unit_method(), )) if name.endswith('_label_key'): _field = name.replace('_label_key', '_input') return self._meta.get_field(_field).verbose_name if name.endswith('_label_value'): _field = name.replace('_label_value', '_input') _unit_field = name.replace('_label_value', '_unit') _val = getattr(self, _field) _method_name = u'get_%s_display' % _unit_field _unit_method = getattr(self, _method_name) return u'%s %s' % (_val, _unit_method(), ) return super(UnitModelMixin, self).__getattr__(name)
def __unicode__(self): if self.discount_type == DISCOUNT_AMOUNT: discount = moneyfmt(self.discount) else: discount = u'%s%%' % floatformat(self.discount) return u'%s off %s or more' % (discount, moneyfmt(self.cart_minimum))
def _check_for_i18n(value, float_formatted, string_formatted): """ Use the i18n enabled defaultfilters.floatformat if possible """ if settings.USE_L10N: return defaultfilters.floatformat(value, 1), string_formatted return value, float_formatted
def add_useritem_into_group(url, group_id): source_obj, scraper, url = validate(url) try: item = OriginalItem.objects.get(url=url) result = scraper.scrape(url) except Exception as e: result = scraper.scrape(url) result['data']['info']['url'] = result['url'] item = OriginalItem(source=source_obj, **result['data']['info']) item.save() tpl_data = dict( base_price=0.0, discount_price=00 ) tpl_data.update(result['data']['price']) item_price = ItemPrice( item=item, current_price=min(filter(lambda x: x > 0, tpl_data.values()) or (0.0,)), **tpl_data ) item_price.save() user_item = UserItem.objects.create(group_id=group_id, item=item, custom_name=item.title) partner = item.source.partner item_price.current_price = defaultfilters.floatformat(item_price.current_price, 2) item = json.loads(serializers.serialize("json", [item]))[0] price = json.loads(serializers.serialize("json", [item_price]))[0] user_item = json.loads(serializers.serialize('json', [user_item]))[0] partner = json.loads(serializers.serialize('json', [partner]))[0] price['formatted_date'] = defaultfilters.date(item_price.created_date.replace(tzinfo=utc), u"d E Y г. H:i") return dict(item=item, price=price, user_item=user_item, partner=partner)
def __init__(self, *args, **kwargs): """ DownPaymentInvoices line items are currently computed on intitialization because of their translations. """ super(DownPaymentInvoice, self).__init__(*args, **kwargs) if self.current_revision and self.id: if self.related_to.is_quotation(): description = _("%(percentage)s%% down-payment on quotation %(reference)s") elif self.related_to.is_purchase_order(): description = _("%(percentage)s%% down-payment on purchase order %(reference)s") self.current_revision.line_items.append( InvoiceItem( reference=self.ITEM_REFERENCE, description=description % { "percentage": floatformat(float(self.percentage * 100), -2), "reference": self.related_to.reference }, quantity=1, unit_price=(self.amount / (Decimal('1.00') + self.tax_applied.rate)).quantize(Decimal('1.00'), ROUND_HALF_UP), tax=self.tax_applied ) ) # Can differ but should not be considered as changed self.current_revision._clear_changed_fields()
def get_subtotal(self): # subtotal = self.selection_set.all().aggregate(Sum('item__price')) subtotal = 0 from django.template.defaultfilters import floatformat for selection in self.selection_set.all(): subtotal += (selection.item.price * selection.quantity) return floatformat(subtotal,2)