Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

django-multilingual-model

A very simple abstract base class, enabling translation of (specific) model fields with only about 33 lines of code.

Example:

models.py

    from django.db import models
    from multiling import MultilingualModel
   
    class Language(models.Model):
        code = models.CharField(max_length=5)
        name = models.CharField(max_length=16)
       
    class BookTranslation(models.Model):
        language = models.ForeignKey("Language")
        title = models.CharField(max_length=32)
        description = models.TextField()
        model = models.ForeignKey("Book")
       
    class Book(MultilingualModel):
        ISBN = models.IntegerField()
       
        class Meta:
            translation = BookTranslation
            multilingual = ['title', 'description']
>>> lang_en = Language(code="en", name="English")
>>> lang_en.save()
>>> lang_pl = Language(code="pl", name="Polish")
>>> book = Book(ISBN="1234567890")
>>> book.save()
>>> book_en = BookTranslation()
>>> book_en.title = "Django for Dummies"
>>> book_en.description = "Django described in simple words."
>>> book_en.model = book
>>> book_en.save()
>>> book_pl = BookTranslation()
>>> book_pl.title = "Django dla Idiotow"
>>> book_pl.description = "Django opisane w prostych slowach"
>>> book_pl.model = book
>>> book_pl.save()
>>>
>>> # now here comes the magic
>>> book.title_en
u'Django for Dummies'
>>> book.description_pl
u'Django opisane w prostych slowach'

To have it interated with Django Admin nicely, try this:

admin.py

from django.contrib import admin
import models

class BookTranslationInline(admin.StackedInline):
   model = models.BookTranslation
   extra = 1
   min_num = 1


class BookAdmin(admin.ModelAdmin):
   list_display = ["ISBN"]
   inlines = [BookTranslationInline]

admin.site.register(models.Book, BookAdmin)

Don't be the product, buy the product!

Schweinderl