Skip to main content

A Django package to add multilingual support to models.

Project description

Lisan - ልሳን

means: A language in Amharic (Ethiopian Language)

Lisan is a Django package that simplifies the process of adding translation support to model fields in Django projects. With Lisan, you can easily manage multilingual content within your Django models, API, and admin interface.

Features

  • Automatic Translation Models: Automatically generate translation models for your fields.
  • Admin Integration: Seamlessly manage translations through the Django admin interface.
  • Fallback Mechanism: Fallback to the default language if a translation is not available.
  • Dynamic Getter Methods: Automatically generate methods to access translated fields.
  • Pluggable Translation Services: Support for external services like Google Translate to automatically translate content.
  • Customizable Admin Display: Configure how translations are displayed in the Django admin interface.
  • Flexible Field Types: Add translation support for various field types like CharField, TextField, and JSONField.

Table of Contents

Installation

You can install Lisan via pip:

pip install lisan

Lisan Settings

1. Configuring Lisan

To start using Lisan in your project, you need to configure the language settings and middleware in your Django settings file.

Step 1.0: Add Lisan Language Settings

LISAN_DEFAULT_LANGUAGE = 'en'  # Default language for translations
LISAN_ALLOWED_LANGUAGES = ['en', 'am', 'or', 'tg']  # Languages supported by Lisan
LISAN_FALLBACK_LANGUAGES = ['fr', 'es', 'en']  # Customize fallback languages
LISAN_DEFAULT_TRANSLATION_SERVICE = 'yourapp.google_translate_service.GoogleTranslateService'  # Pluggable translation service

Step 1.1: Add Lisan Middleware

Make sure to include Lisan's middleware in your MIDDLEWARE settings for automatic language detection and management:

MIDDLEWARE = [
    ...
    'lisan.middleware.LanguageMiddleware',  # Lisan middleware for handling language preferences
    'django.middleware.common.CommonMiddleware',
    ...
]

Usage

1. Adding Translation Support to Models

To add translation support to a model, simply inherit from LisanModelMixin and specify which fields should be translatable using the lisan_fields attribute.

Example:

from django.db import models
from lisan import LisanModelMixin

class Snippet(LisanModelMixin, models.Model):
    lisan_fields = ['title', 'description']  # Fields to be translated
    title = models.CharField(max_length=100, blank=True, default='')
    description = models.TextField(blank=True, default='')
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created']

Once the model is defined, run the following commands to create and apply migrations:

python manage.py makemigrations
python manage.py migrate

2. Managing Translations in Django Admin

To enable translation management in the Django admin, use LisanAdminMixin in your admin class.

Example:

from django.contrib import admin
from lisan import LisanAdminMixin
from .models import Snippet

@admin.register(Snippet)
class SnippetAdmin(LisanAdminMixin, admin.ModelAdmin):
    list_filter = ('created',)
    ordering = ('-created',)
    lisan_display_format = "{field_name} ({language_code})"  # Customizable admin display format

3. Accessing Translations in Code

You can set and get translations using the provided methods.

Setting a Translation

snippet = Snippet.objects.create(title="Code Snippet Example", description="Example Description")
snippet.set_lisan('am', title="ኮድ ቅርጸት ምሳሌ", description="እንቁ ምሳሌ")

Getting a Translation with Fallback and Auto-Translate

You can retrieve translations with a fallback mechanism or even auto-translate content using an external service.

amharic_title = snippet.get_lisan_field('title', 'am', auto_translate=True)
print(amharic_title)  # Output: ኮድ ቅርጸት ምሳሌ (if available) or the auto-translated version

english_title = snippet.get_lisan_field('title', 'en')
print(english_title)  # Output: Code Snippet Example

API Usage

Here is how to use the API to create and retrieve a translated snippet.

1. Creating a Snippet with Translations

To create a snippet with translations, send a POST request to the appropriate API endpoint with the following payload:

Request Body:

{
    "title": "Code Snippet Example",
    "description": "Example Description",
    "translations": [
        {
            "language_code": "am",
            "title": "ኮድ ቅርጸት ምሳሌ",
            "description": "እንቁ ምሳሌ"
        }
    ]
}

2. Retrieving a Snippet with a Specific Translation

To retrieve a snippet in a specific language, send a GET request with the appropriate Accept-Language header to specify the desired language (e.g., am for Amharic).

Request Example:

GET /api/snippets/1/
Accept-Language: am

The response will return the snippet information in the requested language if available, or it will fallback to the default language:

Response Example:

{
    "id": 1,
    "title": "ኮድ ቅርጸት ምሳሌ",
    "description": "እንቁ ምሳሌ"
}

Handling User Preferences for Translations

You can dynamically handle user preferences for translations based on the Accept-Language header or custom user settings.

class SnippetSerializer(LisanSerializerMixin, serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ['id', 'title', 'description']

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        request = self.context.get('request')
        language_code = request.headers.get('Accept-Language', 'en')
        representation['title'] = instance.get_lisan_field('title', language_code)
        return representation

Pluggable Translation Services

The Lisan package supports pluggable translation services, allowing you to integrate with third-party APIs like Google Translate for automatic translations. You can configure this via the LISAN_DEFAULT_TRANSLATION_SERVICE setting.

Creating Custom Translation Services

You can create custom translation services by implementing the BaseTranslationService class.

Example using Google Translate:

# google_translate_service.py
from googletrans import Translator
from lisan.translation_services import BaseTranslationService

class GoogleTranslateService(BaseTranslationService):
    def __init__(self):
        self.translator = Translator()

    def translate(self, text, target_language):
        return self.translator.translate(text, dest=target_language).text

Setting up the Service

To configure your application to use this service, simply set it in the LISAN_DEFAULT_TRANSLATION_SERVICE setting in settings.py:

LISAN_DEFAULT_TRANSLATION_SERVICE = 'yourapp.google_translate_service.GoogleTranslateService'

Testing Translations

To ensure that your translations are handled correctly, here’s an example of how you can write tests for translated fields:

from django.test import TestCase
from .models import Snippet

class SnippetTestCase(TestCase):
    def setUp(self):
        self.snippet = Snippet.objects.create(title="Hello World", description="Description Example")

    def test_translation_set(self):
        self.snippet.set_lisan('fr', title="Bonjour le monde", description="Exemple de description")
        self.assertEqual(self.snippet.get_lisan_field('title', 'fr'), "Bonjour le monde")

    def test_fallback(self):
        # Test that it falls back to English if no French translation is available
        self.assertEqual(self.snippet.get_lisan_field('title', 'fr'), "Hello World")

This testing structure ensures that your translations work as expected, using both direct translations and fallback mechanisms when translations are unavailable.

Contributing

If you find any issues or have suggestions for improvements, feel free to open an issue or submit a pull request on GitHub. Contributions are always welcome.

License

Lisan is licensed under the MIT License. See the LICENSE file for more information.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lisan-0.1.1.tar.gz (17.6 kB view details)

Uploaded Source

Built Distribution

lisan-0.1.1-py3-none-any.whl (18.4 kB view details)

Uploaded Python 3

File details

Details for the file lisan-0.1.1.tar.gz.

File metadata

  • Download URL: lisan-0.1.1.tar.gz
  • Upload date:
  • Size: 17.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.3

File hashes

Hashes for lisan-0.1.1.tar.gz
Algorithm Hash digest
SHA256 c35fd482a4d44afbb65e8f49c073ead4d32cf5e12d133dafa86f4723b99bfdb6
MD5 5da1cda300d8d55dacf587a9661bf073
BLAKE2b-256 96ab145c2dc4fb026634dc4fa77f83463a8a65d682a2312ff2348dd4005791f3

See more details on using hashes here.

File details

Details for the file lisan-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: lisan-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 18.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.3

File hashes

Hashes for lisan-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c944e6921db082249c7de345457fcef58a25dcd9c71eeee521d1dcf038296fb5
MD5 e96cc08be5a18ce356116d0288ae8f3f
BLAKE2b-256 991ef75cbf4a9601fa8f22cc58744ca16bf10dc0f5785df29ab7fbd12ecd131e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page