Multilingual By Choice Pt.2

Tuesday, 08 Sep, 2009 - django, multilingual

Ever since the previous part of the tutorial we have a powerful multilingual-by-choice blog app (yeah, right...).

But, no matter how awesome the app, it has a weakness. How can we make the admin know if we are using the multilingual version or not? django.contrib.admin is awesome itself, but it will need our help to figure it out.

We already have our IS_MULTILINGUAL option available in our settings.py file, so we can use that to choose to import multilingual or not.

For the admin class to be multilingual, it has to inherit from multilingual.ModelAdmin instead of admin.ModelAdmin. So we'll add the logic so the class knows from where to inherit.

if settings.IS_MULTILINGUAL: import multilingual admin_info = { 'class': multilingual.ModelAdmin, } else: admin_info = { 'class': admin.ModelAdmin, }

class PostAdmin(admin_info['class']):
    pass

And voila! Depending on the IS_MULTILINGUAL, the app is smart enough to tell the admin class from where to inherit.

Wait though, what about the SlugField? How are we gonna have admin prepopulate that? Simple, we add another option to our admin_info:

if settings.IS_MULTILINGUAL: import multilingual admin_info = { 'class': multilingual.ModelAdmin, 'suffix': '_en' } else: admin_info = { 'class': admin.ModelAdmin, 'suffix': '' }

class PostAdmin(admin_info['class']):
    prepopulated_fields = {'slug': (''.join(['name', admin_info['suffix']]),)}

And we're done. We choose the inheritance class and from where the SlugField gets prepopulated dynamically (well, sorta, it's actually by the IS_MULTILINGUAL setting).

Comments

Comments for this entry are closed. If you wish to further discuss this post, please contact us directly.