Package: drf-localize
🌐 DRF LocalizePackage to provide localization experiences for mobile and api applications.⚡️ Features✅ Localize keys for multiple languages✅ Generate localizableiOS,Android,Webcompatiblezip&files✅ ModelJSONbased fields localization✅ Library for localizable keys✅ REST API for localizable keys✅ Configurable🔐 InstallationUse the package managerpipto install drf_localize.pipinstalldrf_localizethen add it to your installed apps:INSTALLED_APPS=[...,'drf_localize',...,]then run migrate:pythonmanage.pymigrateand load initial data:pythonmanage.pyloaddatalocalizelanguages
pythonmanage.pyloaddatalocalizekeys(optional)🔨 ConfigurationConfiguration forDRF Localizeis namespaced in a single django setting, namedDRF_LOCALIZE, by default everything is configured out of the box.DRF_LOCALIZE={'LANGUAGES':'ALL',# noqa'BASE_DIR':BASE_DIR,# noqa'API_KEY_HEADER_NAME':'HTTP_X_API_KEY','PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination','KEY_MODEL_CLASS':'drf_localize.models.LocalizeKey','LANGUAGE_MODEL_CLASS':'drf_localize.models.LocalizeLanguage','LANGUAGE_MODEL_CLASS_FIELD':'code',}🔎 Available SettingsHeaderDescriptionDefaultLANGUAGESSpecify language codes to use as array.ALLBASE_DIRSpecify internal directory path.BASE_DIRAPI_KEY_HEADER_NAMESpecifyX-API-Keyheader.HTTP_X_API_KEYPAGINATION_CLASSSpecify pagination class.rest_framework.pagination.PageNumberPaginationKEY_MODEL_CLASSSpecify key model class, must comply todrf_localizekey model.drf_localize.models.LocalizeKeyLANGUAGE_MODEL_CLASSSpecify language model class.drf_localize.models.LocalizeLanguageLANGUAGE_MODEL_CLASS_FIELDSpecify language model class code field.code🔧 UsageSpecifylocalizefields in your modelfromdjango.dbimportmodelsclassBlog(models.Model):# noqa# DRF Localize model specific constant, which is used to translate model fieldsLOCALIZE_TRANSLATE=['title']# or LOCALIZE_TRANSLATE = ['title', 'description']# DRF Localize model specific constant, which is used to store translations (json)LOCALIZE_FIELD='i18n'# DRF Localize model specific constant, which is used to auto-update or remove translations for languagesLOCALIZE_AUTO_UPDATE=False# not required , defaults to False# Your custom model fieldstitle=models.CharField(max_length=254,null=True)description=models.CharField(max_length=512,null=True)# Referenced json field to store translationsi18n=models.JSONField(default=dict)InheritI18NModelSerializerin your model serializerfromapps.blog.modelsimportBlog# noqafromdrf_localize.serializersimport(I18NModelSerializer)classBlogSerializer(I18NModelSerializer):classMeta:model=Blogfields='__all__'Use your model serializer in your endpoints as usualfromapps.blog.modelsimportBlog# noqafromapps.blog.serializersimportBlogSerializer# noqafromrest_framework.viewsetsimportGenericViewSetfromrest_framework.genericsimport(ListAPIView,CreateAPIView,RetrieveUpdateDestroyAPIView,)classBlogViewSet(ListAPIView,CreateAPIView,RetrieveUpdateDestroyAPIView,GenericViewSet):queryset=Blog.objects.all()serializer_class=BlogSerializer📈 REST APIStandalone modeIf you are planning to usedrf_localize's REST API endpoints add package urls in your project.fromdjango.urlsimport(include,path,)urlpatterns=[...,path('drf_localize',include('drf_localize.urls',namespace='localize')),...,]Create localize keyPOST /drf_localize/localize/keysParameterTypeDescriptioncodestringRequired.Uniquei18nobjectOptional.{"code":"DRF Localize","i18n":{"en":"DRF Localize","ro":"DRF Localizare","ru":"DRF Локализация"}}Update localize keyPATCH /drf_localize/localize/keys/:idParameterTypeDescription:idstringRequired.codestringRequired.Uniquei18nobjectOptional.{"i18n":{"en":"DRF Localizes","ro":"DRF Localizare","ru":"DRF Локализация"}}Create localize namespace keyPOST /drf_localize/localize/keysParameterTypeDescriptioncodestringRequired.Uniquei18nobjectOptional.typestringRequired.{"code":"global","i18n":{"en":{"localize":"DRF Localizes"},"ro":{"localize":"DRF Localizare"},"ru":{"localize":"DRF Локализация"}},"type":"NAMESPACE"}Update localize namespace keyPATCH /drf_localize/localize/keys/:idParameterTypeDescription:idstringRequired.codestringRequired.Uniquei18nobjectOptional.typestringRequired.{"i18n":{"en":{"localize":"DRF Localize"},"ro":{"localize":"DRF Localizare"},"ru":{"localize":"DRF Локализация"}},"type":"NAMESPACE"}Retrieve localize namespace keysGET /drf_localize/localize/keys?search=NAMESPACEDownload platform specific localize key fileGET /drf_localize/localize/keys/:platform/:language/fileParameterTypeDescription:platformstringRequired.ios/android/web:languagestringRequired.en/ any other language codeDownload platform specific localize keys zip fileGET /drf_localize/localize/keys/:platform/zipParameterTypeDescription:platformstringRequired.ios/android/webDownload all platform specific localize keys in a single zip fileGET /drf_localize/localize/keys/zipService modeYou will need to add a middleware class:# This middleware listens to `X-API-Key` key header value and finds your application.MIDDLEWARE=[...,'drf_localize.middlewares.LocalizeApplicationMiddleware',...,]then addX-API-Keyheader in standalone mode endpoints:HeaderTypeDescriptionX-API-KeystringRequired. Your application keyCreate applicationPOST /drf_localize/localize/applicationsParameterTypeDescriptiontitlestringOptional.descriptionstringOptional.Retrieve applicationGET /drf_localize/localize/applicationHeaderTypeDescriptionX-API-KeystringRequired. Your application keyAttach application languagesPOST /drf_localize/localize/application/languagesParameterTypeDescriptionlanguages_idarrayRequired.HeaderTypeDescriptionX-API-KeystringRequired. Your application key{"languages_id":[2,1]}Detach application languagesDELETE /drf_localize/localize/application/languagesParameterTypeDescriptionlanguages_idarrayRequired.HeaderTypeDescriptionX-API-KeystringRequired. Your application key{"languages_id":[1]}Retrieve application languagesGET /drf_localize/localize/application/languagesHeaderTypeDescriptionX-API-KeystringRequired. Your application key[{"code":"ab","name":"Abkhaz","native":"аҧсуа"}]📦️ Libraryfromdrf_localizeimportlocalize# Set translatable key translation.localize.set_key('Welcome').set_en('Welcome').set_ro('Bine ati venit').set_pt('Receber')# noqa# Set translatable namespace translation.localize.set_key_namespace('common').set_en({'welcome':'Welcome','order':'Order'}).set_ro({'welcome':'Bine ati venit','order':'Ordin'}).set_pt({'welcome':'Receber','order':'Pedido'})# Build 'en' translation file for iOSlocalize.build(language='en')file=localize.to_platform(platform='IOS')# noqa# Build translations zip file for iOSfile=localize.build_zip(platform='IOS')# noqa# Build translations zip file for ANDROIDfile=localize.build_zip(platform='ANDROID')# noqa# Build translations zip file for WEBfile=localize.build_zip(platform='WEB')# noqa# Build translations zip file for every platformfile=localize.build_zip()# noqa📌 Library helpers# from drf_localize import localize_key_typeclassLocalizeKeyType:KEY_NAMESPACE='NAMESPACE'KEY_PLAIN='PLAIN'KEY_TYPES=[KEY_NAMESPACE,KEY_PLAIN]KEY_CHOICES=((KEY_NAMESPACE,KEY_NAMESPACE),(KEY_PLAIN,KEY_PLAIN))# from drf_localize import localize_platformclassLocalizePlatform:PLATFORM_IOS='IOS'PLATFORM_ANDROID='ANDROID'PLATFORM_WEB='WEB'PLATFORM_TYPES=[PLATFORM_IOS,PLATFORM_ANDROID,PLATFORM_WEB]PLATFORM_CHOICES=((PLATFORM_IOS,PLATFORM_IOS),(PLATFORM_ANDROID,PLATFORM_ANDROID),(PLATFORM_WEB,PLATFORM_WEB))⚗️ Internal Serializer ClassesUsesI18Nserializer to transform localize fieldInherit thisI18NModelSerializerserializer in your model serializerfromrest_framework.serializersimportModelSerializerclassI18NModelSerializer(ModelSerializer):# noqa...Transforms localize field into i18n json field with translationsfromrest_framework.serializersimportSerializerclassI18N(Serializer):# noqa...👥 ContributingPull requests are always appreciated. Open issues addressing pull requests.Flow:Fork itCreate your feature branch (git checkout -b my-new-feature)Test your changes to the best of your ability.Update the documentation to reflect your changes if they add or changes current functionality.Commit your changes (git commit -am 'Added some feature').Push to the branch (git push origin my-new-feature)Create new Pull Request