Skip to content

Instantly share code, notes, and snippets.

@eluttner
Forked from igorsobreira/formatters.py
Created October 5, 2015 21:53
Show Gist options
  • Save eluttner/3123b2e55dd1903324c4 to your computer and use it in GitHub Desktop.
Save eluttner/3123b2e55dd1903324c4 to your computer and use it in GitHub Desktop.
Django form field for Brazilian Real (R$)
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
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'}
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