-
-
Save eluttner/3123b2e55dd1903324c4 to your computer and use it in GitHub Desktop.
Django form field for Brazilian Real (R$)
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.template.defaultfilters import floatformat | |
from django.contrib.humanize.templatetags.humanize import intcomma | |
from django.utils.encoding import force_unicode | |
def decimal_to_real(value, precision=2): | |
''' | |
Receives a Decimal instance and returns a string formatted as brazilian Real currency: | |
12,234.00. Without the "R$". | |
''' | |
value = floatformat(value, precision) | |
value, decimal = force_unicode(value).split('.') | |
value = intcomma(value) | |
value = value.replace(',', '.') + ',' + decimal | |
return value |
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 import forms | |
from widgets import RealCurrencyInput | |
class RealCurrencyField(forms.DecimalField): | |
widget = RealCurrencyInput | |
def clean(self, value): | |
if value: | |
value = value.replace('.', '').replace(',','.') | |
return super(RealCurrencyField, self).clean(value) | |
def widget_attrs(self, widget): | |
return {'class':'real_currency'} | |
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 decimal import Decimal | |
from django import forms | |
from django.utils.safestring import mark_safe | |
from formatters import decimal_to_real | |
class RealCurrencyInput(forms.TextInput): | |
def render(self, name, value, attrs=None): | |
value = value or '' | |
if isinstance(value, Decimal): | |
value = decimal_to_real(str(value), 2) | |
attrs = attrs or {} | |
attrs['class'] = 'real' | |
attrs['alt'] = 'decimal' | |
html = super(RealCurrencyInput, self).render(name, value, attrs) | |
return mark_safe(u"R$ " + html) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment