def test_conversion_fail_when_currency_from_does_not_exist(self): RateSource.objects.create(name="fake-backend") with self.assertRaises(CurrencyConversionException) as cm: convert_money(10.0, "PLN", "EUR") self.assertIn("Rate for PLN in fake-backend do not exists", str(cm.exception))
def test_conversion_fail_when_currency_from_does_not_exist(set_up): RateSource.objects.create(name="fake-backend") with pytest.raises(CurrencyConversionException) as cm: convert_money(10.0, "PLN", "EUR") assert "Rate for PLN in fake-backend do not exists" in str(cm.value)
def test_conversion_fail_when_currency_to_does_not_exist(self): source = RateSource.objects.create(name="fake-backend") Rate.objects.create(source=source, currency="PLN", value=0.99999) with self.assertRaises(CurrencyConversionException) as cm: convert_money(10.0, "PLN", "EUR") self.assertIn("Rate for EUR in fake-backend do not exists", str(cm.exception))
def test_conversion_fail_when_currency_to_does_not_exist(set_up): source = RateSource.objects.create(name="fake-backend") Rate.objects.create(source=source, currency="PLN", value=0.99999) with pytest.raises(CurrencyConversionException) as cm: convert_money(10.0, "PLN", "EUR") assert "Rate for EUR in fake-backend do not exists" in str(cm.value)
def test_conversion_works_from_base_currency(self): source = RateSource.objects.create(name="fake-backend", base_currency="USD") Rate.objects.create(source=source, currency="USD", value=1) Rate.objects.create(source=source, currency="EUR", value=0.74) amount = convert_money(1, "USD", "EUR") self.assertEqual(amount, Decimal("0.74"))
def test_conversion_is_working_from_other_currency(self): source = RateSource.objects.create(name="fake-backend", base_currency="USD") Rate.objects.create(source=source, currency="PLN", value=3.07) Rate.objects.create(source=source, currency="EUR", value=0.74) amount = convert_money(10.0, "PLN", "EUR") self.assertEqual(amount, moneyed.Money(Decimal("2.41"), "EUR"))
def convert_money_object(obj, currency): for field in obj._meta.get_fields(): if isinstance(field, MoneyField): field_instance = getattr(obj, field.name) if field_instance: setattr(obj, field.name, convert_money(field_instance.amount, field_instance.currency, currency)) return obj
def _convert_to_local_currency(self, other): """ Converts other Money instances to the local currency """ if AUTO_CONVERT_MONEY: return convert_money(other.amount, other.currency, self.currency) else: return other
def test_conversion_works_from_base_currency(self): source = RateSource.objects.create(name="fake-backend", base_currency="USD") Rate.objects.create(source=source, currency="USD", value=1) Rate.objects.create(source=source, currency="EUR", value=0.74) amount = convert_money(1, "USD", "EUR") self.assertEqual(type(amount), moneyed.Money) self.assertEqual(amount, moneyed.Money(Decimal("0.74"), "EUR"))
def set_currency(request, price): """ usado para poder estilizar el precio y el currency. un template tag si puede devolver html, miestras q es custom filter solo puede devolver str """ currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY) money = convert_money(price, settings.DEFAULT_CURRENCY, currency_session) return {'amount': '%d' % money.amount, 'currency': money.currency}
def money_to_default(value): """ Convert 'value' to the system default currency. Returns a Money instance """ if not has_default_currency(value): default_currency = get_default_currency() value = convert_money(value.amount, value.currency.code, default_currency.code) return to_money(value)
def convert_money_object(obj, currency): for field in obj._meta.get_fields(): if isinstance(field, MoneyField): field_instance = getattr(obj, field.name) if field_instance: setattr( obj, field.name, convert_money(field_instance.amount, field_instance.currency, currency)) return obj
def save(self, *args, **kwargs): for field in self._meta.fields: if isinstance(field, MoneyField): field_instance = getattr(self, field.name) if not field_instance: continue if field_instance.currency != 'USD': setattr(self, field.name, convert_money(field_instance.amount, field_instance.currency, 'USD')) super(FinancialYear, self).save(*args, **kwargs)
def render(self, context): price = self.price.resolve(context) if not isinstance(price, Decimal): price = Decimal(price) try: money = convert_money(price, self.price_currency.resolve(context), self.currency.resolve(context)) patched_money = MoneyPatched._patch_to_current_class(money) if self.decimal: patched_money.decimal_places = self.decimal.resolve(context) return patched_money except template.VariableDoesNotExist: return ''
def stany_mag_ue(request): with open('b2b_stocks.csv', "w", newline='') as csv_file: writer = csv.writer(csv_file, delimiter=';') writer.writerow([ 'Name', 'SAP', 'EAN', 'Manufacturer', 'Size', 'Model', 'Season', 'Type', 'DOT', 'EUR [Netto]', 'Stock' ]) products = Product.objects.all().values_list( 'name', 'sap', 'ean', 'manufacturer', 'size', 'model', 'season', 'typ', 'dot', 'price', 'stock').order_by('sap').filter(available=True) car_type = "" for product in products: price_eur = convert_money(product[9], "PLN", "EUR") if product[6] == "Lato": season = "Summer" if product[6] == "Zima": season = "Winter" if product[6] == "CAŁOROCZNE": season = "All season" if product[7] == "OSOB": car_type = "Passenger" if product[7] == "BUS": car_type = "Light truck" if product[7] == "CIĘŻAROWE": car_type = "Heavy truck" if product[7] == "4x4" or product[7] == "SUV": car_type = "Off road" writer.writerow([ product[0], product[1], product[2], product[3], product[4], product[5], season, car_type, product[8], price_eur, product[10] ]) # Upload plików serverG = "178.217.140.125" directoryG = "/" filenameUE = "b2b_stocks.csv" ftpG = FTP(serverG) # Set server address ftpG.login("stany_ph", "1qazxsW@") # Connect to server ftpG.cwd(directoryG) # Move to the desired folder in server ftpG.storbinary('STOR ' + filenameUE, open(filenameUE, 'rb')) # Download file from server ftpG.close() # Close connection return render(request, 'shop/product/get.html')
def _convert_to_local_currency(self, other): """ Converts other Money instances to the local currency. If django-money-rates is installed we can automatically perform operations with different currencies """ if getattr(settings, 'AUTO_CONVERT_MONEY', False): if 'djmoney_rates' in settings.INSTALLED_APPS: try: from djmoney_rates.utils import convert_money return convert_money(other.amount, other.currency, self.currency) except ImportError: raise ImproperlyConfigured('djmoney_rates doesn\'t support Django 1.9+') raise ImproperlyConfigured('You must install djmoney-rates to use AUTO_CONVERT_MONEY = True') return other
def convert_money(value, currency): """ Converts other Money instances to the local currency. If django-money-rates is installed we can automatically perform operations with different currencies. """ if getattr(settings, 'AUTO_CONVERT_MONEY', False): if 'djmoney_rates' in settings.INSTALLED_APPS: try: from djmoney_rates.utils import convert_money return convert_money(value.amount, value.currency, currency) except ImportError: raise ImproperlyConfigured('djmoney_rates doesn\'t support Django 1.9+') raise ImproperlyConfigured('You must install djmoney-rates to use AUTO_CONVERT_MONEY = True') return value
def render(self, context): price = self.price.resolve(context) if not isinstance(price, Decimal): price = Decimal(price) try: money = convert_money( price, self.price_currency.resolve(context), self.currency.resolve(context) ) patched_money = MoneyPatched._patch_to_current_class(money) if self.decimal: patched_money.decimal_places = self.decimal.resolve(context) return patched_money except template.VariableDoesNotExist: return ''
def __sub__(self, other): if isinstance(other, F): return other.__rsub__(self) other = convert_money(other, self.currency) return super(Money, self).__sub__(other)
def portfolio(request, pk): customer = get_object_or_404(Customer, pk=pk) customers = Customer.objects.filter(created_date__lte=timezone.now()) investments = Investment.objects.filter(customer=pk) stocks = Stock.objects.filter(customer=pk) sum_acquired_value = Investment.objects.filter(customer=pk).aggregate( sum=Sum('acquired_value'))['sum'] sum_recent_value = Investment.objects.filter(customer=pk).aggregate( sum=Sum('recent_value'))['sum'] # Initialize the value of the stocks sum_current_stocks_value = 0 sum_of_initial_stock_value = 0 # Loop through each stock and add the value to the total for stock in stocks: sum_current_stocks_value += stock.current_stock_value() sum_of_initial_stock_value += stock.initial_stock_value() #Converting all values to decimals sum_current_stocks_value = decimal.Decimal(sum_current_stocks_value) sum_of_initial_stock_value = decimal.Decimal(sum_of_initial_stock_value) sum_acquired_value = decimal.Decimal(sum_acquired_value) sum_recent_value = decimal.Decimal(sum_recent_value) # Adding variables for total sum of inital and current value sum_initial_total = decimal.Decimal( sum_of_initial_stock_value) + decimal.Decimal(sum_acquired_value) sum_current_total = decimal.Decimal( sum_current_stocks_value) + decimal.Decimal(sum_recent_value) #Adding code to convert value into euros sum_initial_total_euros = convert_money(sum_initial_total, "USD", "EUR") sum_current_total_euros = convert_money(sum_current_total, "USD", "EUR") sum_initial_total_rubels = convert_money(sum_initial_total, "USD", "RUB") sum_current_total_rubels = convert_money(sum_current_total, "USD", "RUB") #Building the objects for teh graph data = [['Time', 'Investment', 'Stock', 'Total'], [ 'Initial', sum_acquired_value, sum_of_initial_stock_value, sum_initial_total ], [ 'Current', sum_recent_value, sum_current_stocks_value, sum_current_total ]] # DataSource object data_source = SimpleDataSource(data=data) #queryset = Customer.objects.filter(pk=pk) #data_source_new = ModelDataSource(queryset, fields=['year', 'sales']) # Chart object chart = LineChart(data_source) context = {'chart': chart} return render( request, 'portfolio/portfolio.html', { 'customers': customers, 'investments': investments, 'stocks': stocks, 'sum_acquired_value': sum_acquired_value, 'sum_recent_value': sum_recent_value, 'sum_current_stocks_value': sum_current_stocks_value, 'sum_of_initial_stock_value': sum_of_initial_stock_value, 'sum_initial_total': sum_initial_total, 'sum_current_total': sum_current_total, 'sum_initial_total_euros': sum_initial_total_euros, 'sum_current_total_euros': sum_current_total_euros, 'sum_initial_total_rubels': sum_initial_total_rubels, 'sum_current_total_rubels': sum_current_total_rubels, 'chart': chart })
def convert(money, currency): """ Convert money object `money` to `currency`.""" return convert_money(money.amount, money.currency, currency)
def test_conversion_fail_when_source_does_not_exist(set_up): with pytest.raises(CurrencyConversionException) as cm: convert_money(10.0, "PLN", "EUR") assert "Rate for fake-backend source do not exists" in str(cm.value)
def set_currency(value, request): currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY) money = convert_money(value, settings.DEFAULT_CURRENCY, currency_session) # se puede usar %.2f para mostrar en la plantilla los centavos. 75.50 return '%d %s' % (money.amount, money.currency)
def convert_currency(amount, form, to): c = convert_money(amount, form, to) return c
def test_conversion_fail_when_source_does_not_exist(self): with self.assertRaises(CurrencyConversionException) as cm: convert_money(10.0, "PLN", "EUR") self.assertIn("Rate for fake-backend source do not exists", str(cm.exception))