Esempio n. 1
0
    def to_python(self, value):
        if not isinstance(value, tuple):
            raise Exception("Invalid money input, expected sum and currency.")

        amount = super(MoneyField, self).to_python(value[0])
        currency = value[1]
        if not currency:
            raise forms.ValidationError(_(u'Currency is missing'))
        currency = currency.upper()
        if not CURRENCIES.get(currency, False) or currency == Currency.get_default().code:
            raise forms.ValidationError(_(u"Unrecognized currency type '%s'." % currency))
        return Money(amount=amount, currency=currency)
Esempio n. 2
0
from django import forms
from pymonon import Money, CURRENCIES, Currency
from decimal import Decimal
import operator

__all__ = ('InputMoneyWidget', 'CurrencySelectWidget',)

CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c.code != Currency.get_default()]
CURRENCY_CHOICES.sort(key=operator.itemgetter(1))


class CurrencySelectWidget(forms.Select):
    def __init__(self, attrs=None, choices=CURRENCY_CHOICES):
        super(CurrencySelectWidget, self).__init__(attrs, choices)


class InputMoneyWidget(forms.TextInput):
    def __init__(self, attrs=None, currency_widget=None):
        self.currency_widget = currency_widget or CurrencySelectWidget()
        super(InputMoneyWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        amount = ''
        currency = ''
        if isinstance(value, Money):
            amount = value.amount
            currency = value.currency.code
        if isinstance(value, tuple):
            amount = value[0]
            currency = value[1]
        if isinstance(value, int) or isinstance(value, Decimal):