Created
September 17, 2014 05:17
-
-
Save theskumar/e9d8e8ca09008a25aad4 to your computer and use it in GitHub Desktop.
Django Currency Field (put this in 'myutils' module)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from decimal import Decimal | |
try: | |
from south.modelsinspector import add_introspection_rules | |
except ImportError: | |
SOUTH = False | |
else: | |
SOUTH = True | |
class CurrencyField(models.DecimalField): | |
__metaclass__ = models.SubfieldBase | |
def __init__(self, verbose_name=None, name=None, **kwargs): | |
decimal_places = kwargs.pop('decimal_places', 2) | |
max_digits = kwargs.pop('max_digits', 10) | |
super(CurrencyField, self). __init__( | |
verbose_name=verbose_name, name=name, max_digits=max_digits, | |
decimal_places=decimal_places, **kwargs) | |
def to_python(self, value): | |
try: | |
return super(CurrencyField, self).to_python(value).quantize(Decimal("0.01")) | |
except AttributeError: | |
return None | |
if SOUTH: | |
add_introspection_rules([ | |
( | |
[CurrencyField], | |
[], | |
{ | |
"decimal_places": ["decimal_places", {"default": "2"}], | |
"max_digits": ["max_digits", {"default": "10"}], | |
}, | |
), | |
], ['^myutils\.models\.CurrencyField']) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment