Wednesday, June 16, 2010

Django 1.2.1 Localization

I just finished playing around with django 1.2.1 localization. I did that because after finished upgrading to django 1.2.1, I was amazed with the Indonesian language localization in the admin page. Exactly what I need!
I had a bit trouble working with localization, which turned out that it is related with the language support of the OS, in my case, Ubuntu 10.04. Another thing is that I was doing this on ubuntu live-usb flash. I can take that usbflash, plug it in any computer, boot up, and continue my work.

First of all, go to the following directory and check whether your OS has support for your preferred language.

$ cd /var/lib/locales/supported.d
$ ls

In my case, I did not have 'id' in that directory. So, I had to perform the following:

$ sudo aptitude install language-pack-id-base language-pack-id

Then perform the following:

$ pwd
$ cat id # my preferred language
id_ID.UTF-8 UTF-8

After that let's perform some test in python.

>>> import locale
>>> from datetime import datetime
>>> locale.setlocale(locale.LC_ALL, 'id_ID.UTF-8')
'id_ID.UTF-8' # I took the id_ID.UTF-8 from the content of /var/lib/locales/supported.d/id
>>>'%A %B')
'Rabu Juni'

Right on! Things are working as expected.

Now, it's time to use localization in django forms.
First set the following configuration in
USE_L10N = True

Then, create a simple form which implements localization.

class TestForm(forms.Form):
deposit = forms.DecimalField(localize=True)
tanggal = forms.DateTimeField(localize=True)

...and you are done. All you need to do is just create a view which has an instance of TestForm and bind it a data (dictionary), and then render it.

The neat thing is when you want to display 'Decimal' data in that form, you will see the proper local thousand separator format being displayed. It will also take local format as an input and recognized and convert it properly.

Enjoy django 1.2.1!

No comments:

Post a Comment