Google

Friday, July 24, 2009

At this moment i am writing a django application and in this application reports can be exported to excel files. For CharField everything is ok but for decimal fields it is becoming complicated. Why? because in Turkey, we are using "," as a decimal separator. In database, decimal fields are kept as xx.x and excel is creating problems when it is regional setting adjusted to recognize xx,x as default format. This is typical internalization problem that you can see anywhere. Normally, django project considering this kind of problems.(i.e date filter, you can easily implement your date format with this filter.)But noone can blame Django not to have decimal formats converter filter in template,in fact implementing a decimal filter format converter is so simple in django.
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ in this web page you can see how to write your own custom filter. But maybe you dont like to spend your time while reading long pages.Just look at this django file django/template/defaultfilters.py . This is the file which is containing default filters in django. In this file you need to spend less than five minutes to write your own simple decimal format converter filter.
Problem: 1881.19 -->1881,19 (a filter is needed in template).
Just add below lines to defaultfilters.py
def string2tr(value):
decimaltr=str(value).replace(".",",")
return decimaltr
And register your filter in this file
register.filter(string2tr)

Now whenever you want to convert xx.xx to xx,xx you can use your filter in templates. {{value|strig2tr}}