Created
October 3, 2011 01:38
-
-
Save gilsondev/1258250 to your computer and use it in GitHub Desktop.
Definindo o campo DecimalField no formato 0,00
This file contains hidden or 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
# -*- coding: utf8 -*- | |
""" | |
Script baseado no snippet abaixo: | |
http://djangosnippets.org/snippets/176/ | |
Obs.: Alterei algumas coisas como: | |
* Import newsform para forms; | |
* Aceitar o formato 0,00, sendo que o formato 0.00 é aceitado por padrão. | |
""" | |
import re | |
from django import forms | |
class CurrencyField (forms.RegexField): | |
currencyRe = re.compile(r'^[0-9]{1,5}(,[0-9][0-9])?$') | |
def __init__(self, *args, **kwargs): | |
super(CurrencyField, self).__init__( | |
self.currencyRe, None, None, *args, **kwargs) | |
def clean(self, value): | |
value = super(CurrencyField, self).clean(value) | |
if value.replace(",", "."): | |
new_value = value.replace(",", ".") | |
return float(new_value) | |
class CurrencyInput (forms.TextInput): | |
def render(self, name, value, attrs=None): | |
if value != '': | |
try: | |
value = u"%.2f" % value | |
except TypeError: | |
pass | |
return super(CurrencyInput, self).render(name, value, attrs) |
This file contains hidden or 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
# -*- coding: utf8 -*- | |
from django import forms | |
from utils.currencyfields import CurrencyField, CurrencyInput | |
class MyForm (forms.Form): | |
amount = CurrencyField(widget=CurrencyInput, initial=0) # 0.00 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment