Archive for the 'Django' Category

Django auto-translation of field values

Monday, July 14th, 2008

What’s really nice in Django is the gettext implementation and the _ convention. But when running django-admin.py makemessages we’re not generating any translations for dynamic values such as field values. So let’s say that we have a model and we’d like what’s in it to be displayed in a translated manner. In the new Django development version we’re able to create our own special field types. And we can extend the CharField to provide automatic translation:

1
2
3
4
5
6
7
from django.db import models
from django.utils.translation import gettext_lazy as _
 
class AutoTranslateField(models.CharField):
    __metaclass__ = models.SubfieldBase
    def to_python(self, value):
        return str(_(value))

After that we just add whatever translations we know of to our locale/CODE/LC_MESSAGES/django.po file and run compilemessages.

Tip: Extending Django flatpages

Saturday, July 12th, 2008

I did a Google search and since nothing came up, I’m writing this little tip on creating your own CMS by extending Django’s flatpages. What’s good about flatpages is that they’re included in Django and has some basic code to get you started. But clearly they’re not enough if you want other people to administer a site.. you’ll want to add extra fields and special help texts for the admin. But we still don’t want to rewrite those ~150 lines of code, and they can really help you get past all the boring stuff and into the action.

Simply do the following:

cp -R /usr/share/python-support/python-django/django/contrib/flatpages my_project/my_flatpages

views.py

1
from my_project.my_flatpages.models import FlatPage

middleware.py

1
from my_project.my_flatpages.views import flatpage

urls.py

3
4
5
urlpatterns = patterns('my_project.my_flatpages.views',
    (r'^(?P<url>.*)$', 'flatpage'),
)

my_project.my_flatpages.middleware.FlatpageFallbackMiddleware has to be added to your MIDDLEWARE_CLASSES and my_project.my_flatpages to your INSTALLED_APPS and you’ll need to run manage.py syncdb, possibly changing the table name in models.py, so it doesn’t conflict with the old flatpages table. That’s basically it. After that you can work on the templates as described in the other howto’s, but now you have your own model to extend.