django-restful-translator


Namedjango-restful-translator JSON
Version 0.10.0 PyPI version JSON
download
home_pagehttps://github.com/AlexIvanchyk/django_restful_translator
SummaryA Django application providing translation functionalities for Django Rest Framework
upload_time2024-06-23 10:41:31
maintainerNone
docs_urlNone
authorAlex Ivanchyk
requires_python>=3.9
licenseMIT
keywords django rest-framework translation i18n
VCS
bugtrack_url
requirements Django djangorestframework polib google-cloud-translate boto3 deepl
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # django_restful_translator

`django_restful_translator`is a Django library designed to enhance the internationalization of Django models by providing tools for managing and serving model translations. It integrates seamlessly with the Django REST Framework, offering model translation without altering original model values, and supports automatic translation through external services.



## Functionality

`django_restful_translator` provides:

- **Model translations**: The `TranslatableModel` mixin adds translation capabilities to your models, allowing you to specify which fields should be translatable, while leaving the original field values intact.

- **Translation management**: Admin inlines for managing translations from the Django Admin site.

- **REST API support**: Provided serializers (`TranslatableDBSerializer`, `TranslatableDBDictSerializer`, `TranslatableGettextSerializer`, `TranslatableGettextDictSerializer`, `TranslatableWritableDBDictSerializer`) ensure translated fields are properly serialized in API responses.

- **Translation synchronization**: Commands `drt_makemessages` and `drt_update_database` export translations to `.po` files and import them back into the database, keeping translations synchronized across different environments.

- **Automatic Translation**: The library supports automatic translation of model fields through popular translation providers like Google Translate v2, v3, AWS Translate and Deepl. The feature is configurable and can be run via an admin command.

## Advantages

- **Preserves original values**: `django_restful_translator` stores all translations in a separate model, ensuring that your original model's values remain unchanged.

- **Ease of use**: It integrates seamlessly with the Django Admin interface for easy management of translations.

- **Flexibility**: The `TranslatableModel` mixin can be added to any Django model with specified fields to translate.

- **Efficiency**: By storing translations in the database and only translating fields when necessary, `django_restful_translator` minimizes unnecessary work.

- **Integration with Django REST framework**: If you're using Django REST framework, `django_restful_translator` is designed to work with it out of the box.

## Installation

Use the package manager [pip](https://pip.pypa.io/en/stable/) to install django_restful_translator.

```bash
pip install django-restful-translator
```

## Configuration

In your settings file, add the middleware for handling language preferences:

```python
MIDDLEWARE = [
    ...
    'django.middleware.locale.LocaleMiddleware',
    ...
]
```

In your settings file, add `django_restful_translator` to instaled apps:
```python
INSTALLED_APPS = [
    ...
    'django_restful_translator',
    ...
]
```

Set up your languages and locale paths. Make sure to include both the standard locale directory and the one for django_restful_translator:

```python
LOCALE_PATHS = (
    BASE_DIR / "locale",
    BASE_DIR / "drt_locale",
)

LANGUAGES = (
    ("en", "English"),
    ("sv", "Swedish"),
)

LANGUAGE_CODE = "en"
```
## Migrations
After setting up, you need to create the necessary database tables. You can do this by running migrations:
```bash
python manage.py migrate
```

## Usage

1. Import the `TranslatableModel` in your models.py and use it as a base class for any model you want to be translatable.

```python
from django_restful_translator.models import TranslatableModel

class YourModel(TranslatableModel):
    ...
```

2. Add your translatable fields to the `translatable_fields` attribute.

```python
class YourModel(TranslatableModel):
    title = models.CharField(max_length=100)
    description = models.TextField()

    translatable_fields = ['title', 'description']
```

3. Use the provided serializers in your API.

```python
from django_restful_translator.drf.serializers import TranslatableDBSerializer

class YourModelSerializer(TranslatableDBSerializer):
    ...
```
4. To enable managing translations in the Django admin, add `TranslationInline` to your model admin.
```python
from django_restful_translator.admin import TranslationInline

class YourModelAdmin(admin.ModelAdmin):
    inlines = [TranslationInline,]
```
5. When querying your translatable models, you can optimize your database queries by using `prefetch_related` to prefetch translations.
```python
YourModel.objects.all().prefetch_related('translations')
```
6. Run the provided management commands to generate `.po` files and update the database with translations.

```bash
python manage.py drt_makemessages
```
```bash
python manage.py drt_update_database
```
7. Converting Existing `.po` Files to DRT Format. 
Utilize the management command `drt_convert_locales` to transform existing `.po` files into a format suitable for use with the Django Restful Translator (DRT). The command accepts the following arguments:
- `--locale`: The directory where the existing `.po` files are located and will be read from. 
- `--remove-used`: When this option is used, the entries that are converted and added to the new `.po` file formatted for DRT will be removed from the original `.po` file, keeping it clean from already processed entries.


To convert `.po` files without modifying the original file:

```bash
python manage.py drt_convert_locales --locale locale
```
To remove entries in the original `.po` file that are used/converted in the new DRT format:
```bash
python manage.py drt_convert_locales --locale locale --remove-used
```

## Automatic Translation Feature Guide

### Overview

Our library provides an easy way to automatically translate fields in your Django models using popular translation providers such as Google Translate v2, v3, AWS Translate and DeepL. This guide will help you configure and use this feature.

### Requirements

- Make sure the necessary credentials for your chosen translation provider are available in your Django settings file.

### For Google Translate v2:

You can use the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to provide the location of a credential JSON file.
https://cloud.google.com/docs/authentication/application-default-credentials#GAC

### For Google Translate v3:

You can use the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to provide the location of a credential JSON file.
https://cloud.google.com/docs/authentication/application-default-credentials#GAC

#### Configuring Django Settings
To integrate Google Translate API v3 with your Django application, you need to add the following configuration settings in your settings.py file. These settings will specify your Google Cloud project name and the location for the Translate API:

```python
# settings.py
GOOGLE_CLOUD_PROJECT = 'your google cloud project id'
GOOGLE_CLOUD_LOCATION = 'your google cloud location'
```

### For AWS Translate:

```python
# settings.py
AWS_ACCESS_KEY_ID = 'your aws access key here'
AWS_SECRET_ACCESS_KEY = 'your aws secret access key here'
AWS_REGION_NAME = 'your aws region name here'
```

### For DeepL Translate:

```python
# settings.py
DEEPL_AUTH_KEY = 'your DeepL auth key here'
```

### Running the Admin Command

You can use the provided admin command to translate your model fields. The command accepts the following arguments:

- `--language`: The language code to which you want to translate.
- `--target_language`: The provider target language if it differs from the setting language
- `--provider`: The translation provider to use: `google_v2`, `google_v3`, `aws`, `deepl`.
- `--all`: (Optional) Use this flag if you want to overwrite existing translations.
- `--workers`: (Optional) Number of worker threads to use for concurrent processing. Default is 4.
- `--without_batch`: (Optional) One provider request per one unit of text.

**Run the admin command as follows:**

```bash
python manage.py drt_translate_models --language=es --provider=google_v3
```

This will translate all translatable fields to Spanish using Google Translate.

**To overwrite existing translations:**

```bash
python manage.py drt_translate_models --language=es --provider=google_v3 --all
```

### Verifying Translations

After running the command, your translated text should now be available and stored in your database. You can verify this through your Django admin panel or by querying the models directly.

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## License

[MIT](https://choosealicense.com/licenses/mit/)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/AlexIvanchyk/django_restful_translator",
    "name": "django-restful-translator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "django rest-framework translation i18n",
    "author": "Alex Ivanchyk",
    "author_email": "alexander.ivanchik@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/45/85/285b96ee40cdc25ea43d8aecc632498ed8a132e86f605406113d64db21b0/django_restful_translator-0.10.0.tar.gz",
    "platform": null,
    "description": "# django_restful_translator\n\n`django_restful_translator`is a Django library designed to enhance the internationalization of Django models by providing tools for managing and serving model translations. It integrates seamlessly with the Django REST Framework, offering model translation without altering original model values, and supports automatic translation through external services.\n\n\n\n## Functionality\n\n`django_restful_translator` provides:\n\n- **Model translations**: The `TranslatableModel` mixin adds translation capabilities to your models, allowing you to specify which fields should be translatable, while leaving the original field values intact.\n\n- **Translation management**: Admin inlines for managing translations from the Django Admin site.\n\n- **REST API support**: Provided serializers (`TranslatableDBSerializer`, `TranslatableDBDictSerializer`, `TranslatableGettextSerializer`, `TranslatableGettextDictSerializer`, `TranslatableWritableDBDictSerializer`) ensure translated fields are properly serialized in API responses.\n\n- **Translation synchronization**: Commands `drt_makemessages` and `drt_update_database` export translations to `.po` files and import them back into the database, keeping translations synchronized across different environments.\n\n- **Automatic Translation**: The library supports automatic translation of model fields through popular translation providers like Google Translate v2, v3, AWS Translate and Deepl. The feature is configurable and can be run via an admin command.\n\n## Advantages\n\n- **Preserves original values**: `django_restful_translator` stores all translations in a separate model, ensuring that your original model's values remain unchanged.\n\n- **Ease of use**: It integrates seamlessly with the Django Admin interface for easy management of translations.\n\n- **Flexibility**: The `TranslatableModel` mixin can be added to any Django model with specified fields to translate.\n\n- **Efficiency**: By storing translations in the database and only translating fields when necessary, `django_restful_translator` minimizes unnecessary work.\n\n- **Integration with Django REST framework**: If you're using Django REST framework, `django_restful_translator` is designed to work with it out of the box.\n\n## Installation\n\nUse the package manager [pip](https://pip.pypa.io/en/stable/) to install django_restful_translator.\n\n```bash\npip install django-restful-translator\n```\n\n## Configuration\n\nIn your settings file, add the middleware for handling language preferences:\n\n```python\nMIDDLEWARE = [\n    ...\n    'django.middleware.locale.LocaleMiddleware',\n    ...\n]\n```\n\nIn your settings file, add `django_restful_translator` to instaled apps:\n```python\nINSTALLED_APPS = [\n    ...\n    'django_restful_translator',\n    ...\n]\n```\n\nSet up your languages and locale paths. Make sure to include both the standard locale directory and the one for django_restful_translator:\n\n```python\nLOCALE_PATHS = (\n    BASE_DIR / \"locale\",\n    BASE_DIR / \"drt_locale\",\n)\n\nLANGUAGES = (\n    (\"en\", \"English\"),\n    (\"sv\", \"Swedish\"),\n)\n\nLANGUAGE_CODE = \"en\"\n```\n## Migrations\nAfter setting up, you need to create the necessary database tables. You can do this by running migrations:\n```bash\npython manage.py migrate\n```\n\n## Usage\n\n1. Import the `TranslatableModel` in your models.py and use it as a base class for any model you want to be translatable.\n\n```python\nfrom django_restful_translator.models import TranslatableModel\n\nclass YourModel(TranslatableModel):\n    ...\n```\n\n2. Add your translatable fields to the `translatable_fields` attribute.\n\n```python\nclass YourModel(TranslatableModel):\n    title = models.CharField(max_length=100)\n    description = models.TextField()\n\n    translatable_fields = ['title', 'description']\n```\n\n3. Use the provided serializers in your API.\n\n```python\nfrom django_restful_translator.drf.serializers import TranslatableDBSerializer\n\nclass YourModelSerializer(TranslatableDBSerializer):\n    ...\n```\n4. To enable managing translations in the Django admin, add `TranslationInline` to your model admin.\n```python\nfrom django_restful_translator.admin import TranslationInline\n\nclass YourModelAdmin(admin.ModelAdmin):\n    inlines = [TranslationInline,]\n```\n5. When querying your translatable models, you can optimize your database queries by using `prefetch_related` to prefetch translations.\n```python\nYourModel.objects.all().prefetch_related('translations')\n```\n6. Run the provided management commands to generate `.po` files and update the database with translations.\n\n```bash\npython manage.py drt_makemessages\n```\n```bash\npython manage.py drt_update_database\n```\n7. Converting Existing `.po` Files to DRT Format. \nUtilize the management command `drt_convert_locales` to transform existing `.po` files into a format suitable for use with the Django Restful Translator (DRT). The command accepts the following arguments:\n- `--locale`: The directory where the existing `.po` files are located and will be read from. \n- `--remove-used`: When this option is used, the entries that are converted and added to the new `.po` file formatted for DRT will be removed from the original `.po` file, keeping it clean from already processed entries.\n\n\nTo convert `.po` files without modifying the original file:\n\n```bash\npython manage.py drt_convert_locales --locale locale\n```\nTo remove entries in the original `.po` file that are used/converted in the new DRT format:\n```bash\npython manage.py drt_convert_locales --locale locale --remove-used\n```\n\n## Automatic Translation Feature Guide\n\n### Overview\n\nOur library provides an easy way to automatically translate fields in your Django models using popular translation providers such as Google Translate v2, v3, AWS Translate and DeepL. This guide will help you configure and use this feature.\n\n### Requirements\n\n- Make sure the necessary credentials for your chosen translation provider are available in your Django settings file.\n\n### For Google Translate v2:\n\nYou can use the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to provide the location of a credential JSON file.\nhttps://cloud.google.com/docs/authentication/application-default-credentials#GAC\n\n### For Google Translate v3:\n\nYou can use the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to provide the location of a credential JSON file.\nhttps://cloud.google.com/docs/authentication/application-default-credentials#GAC\n\n#### Configuring Django Settings\nTo integrate Google Translate API v3 with your Django application, you need to add the following configuration settings in your settings.py file. These settings will specify your Google Cloud project name and the location for the Translate API:\n\n```python\n# settings.py\nGOOGLE_CLOUD_PROJECT = 'your google cloud project id'\nGOOGLE_CLOUD_LOCATION = 'your google cloud location'\n```\n\n### For AWS Translate:\n\n```python\n# settings.py\nAWS_ACCESS_KEY_ID = 'your aws access key here'\nAWS_SECRET_ACCESS_KEY = 'your aws secret access key here'\nAWS_REGION_NAME = 'your aws region name here'\n```\n\n### For DeepL Translate:\n\n```python\n# settings.py\nDEEPL_AUTH_KEY = 'your DeepL auth key here'\n```\n\n### Running the Admin Command\n\nYou can use the provided admin command to translate your model fields. The command accepts the following arguments:\n\n- `--language`: The language code to which you want to translate.\n- `--target_language`: The provider target language if it differs from the setting language\n- `--provider`: The translation provider to use: `google_v2`, `google_v3`, `aws`, `deepl`.\n- `--all`: (Optional) Use this flag if you want to overwrite existing translations.\n- `--workers`: (Optional) Number of worker threads to use for concurrent processing. Default is 4.\n- `--without_batch`: (Optional) One provider request per one unit of text.\n\n**Run the admin command as follows:**\n\n```bash\npython manage.py drt_translate_models --language=es --provider=google_v3\n```\n\nThis will translate all translatable fields to Spanish using Google Translate.\n\n**To overwrite existing translations:**\n\n```bash\npython manage.py drt_translate_models --language=es --provider=google_v3 --all\n```\n\n### Verifying Translations\n\nAfter running the command, your translated text should now be available and stored in your database. You can verify this through your Django admin panel or by querying the models directly.\n\n## Contributing\n\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\n## License\n\n[MIT](https://choosealicense.com/licenses/mit/)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Django application providing translation functionalities for Django Rest Framework",
    "version": "0.10.0",
    "project_urls": {
        "Homepage": "https://github.com/AlexIvanchyk/django_restful_translator"
    },
    "split_keywords": [
        "django",
        "rest-framework",
        "translation",
        "i18n"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "81db30924e6ea91c1135622753f862c8a9087afe84dc3441b43b6adfd757d579",
                "md5": "9cd8a96e86122164327c537ac17e5f3d",
                "sha256": "65f1d9e9b8f69710f5eb64aba93391b400ed7e7b9046a55b5c80d633add5e994"
            },
            "downloads": -1,
            "filename": "django_restful_translator-0.10.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9cd8a96e86122164327c537ac17e5f3d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 17462,
            "upload_time": "2024-06-23T10:41:29",
            "upload_time_iso_8601": "2024-06-23T10:41:29.790461Z",
            "url": "https://files.pythonhosted.org/packages/81/db/30924e6ea91c1135622753f862c8a9087afe84dc3441b43b6adfd757d579/django_restful_translator-0.10.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4585285b96ee40cdc25ea43d8aecc632498ed8a132e86f605406113d64db21b0",
                "md5": "ecf7ff21cd1d067cbfee903a582fdcd9",
                "sha256": "cff764aed7dd68a5b86bc2c083cfe5b239fffa6e843602fb2bd6bc93096d8833"
            },
            "downloads": -1,
            "filename": "django_restful_translator-0.10.0.tar.gz",
            "has_sig": false,
            "md5_digest": "ecf7ff21cd1d067cbfee903a582fdcd9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 15924,
            "upload_time": "2024-06-23T10:41:31",
            "upload_time_iso_8601": "2024-06-23T10:41:31.337405Z",
            "url": "https://files.pythonhosted.org/packages/45/85/285b96ee40cdc25ea43d8aecc632498ed8a132e86f605406113d64db21b0/django_restful_translator-0.10.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-23 10:41:31",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "AlexIvanchyk",
    "github_project": "django_restful_translator",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "Django",
            "specs": [
                [
                    ">=",
                    "3.2"
                ]
            ]
        },
        {
            "name": "djangorestframework",
            "specs": [
                [
                    ">=",
                    "3.11"
                ]
            ]
        },
        {
            "name": "polib",
            "specs": [
                [
                    ">=",
                    "1.1"
                ]
            ]
        },
        {
            "name": "google-cloud-translate",
            "specs": [
                [
                    ">=",
                    "2.0.4"
                ]
            ]
        },
        {
            "name": "boto3",
            "specs": [
                [
                    ">=",
                    "1.26.31"
                ]
            ]
        },
        {
            "name": "deepl",
            "specs": [
                [
                    ">=",
                    "1.16.1"
                ]
            ]
        }
    ],
    "lcname": "django-restful-translator"
}
        
Elapsed time: 1.16247s