
Database-Driven Translation Caching Django Template Filter This is a Django template filter designed to cache translations. It uses database models representing the translations and then queries them by text so you can render text in any language on a website, and only translate the text once. I have also included the code I use to translate the text, using NLP Translation from RapidAPI.com, as well as middleware to get the request in a template filter (in order to get the language). This code relies on the browser's language code, as well as a query string, ?lang=, to render the text in the users' languages. I have added comments to describe how the code works. The code begins with some middleware:
# app/middleware.py
from threading import local # Imports
from django.utils.deprecation import MiddlewareMixin
_request = local() # Store the request
class CurrentRequestMiddleware(MiddlewareMixin): # Use a middleware mixin to save the request
def process_request(self, request):
_request.value = request
def get_current_request(): # Return the request
try:
return _request.value
except AttributeError:
return None
# project/settings.py
MIDDLEWARE = [
'blog.middleware.CurrentRequestMiddleware', # The middleware we just made for the request
'django.middleware.locale.LocaleMiddleware' # Middleware to store the language code in the request
]
# app/models.py
from django.db import models
class Translation(models.Model):
id = models.AutoField(primary_key=True)
src = models.CharField(max_length=2, default='en')
lang = models.CharField(max_length=2, default='en')
value = models.TextField(blank=True)
translated = models.TextField(blank=True)
# app/templatetags/app_filters.py
from app.models import Translation # Imports
from app.middleware import get_current_request
from django import template
register = template.Library() # Register the template library
def get_lang(): # Get the language to translate to
request = get_current_request()
lang = request.LANGUAGE_CODE
if(request.GET.get('lang', '') != ''):
lang = request.GET.get('lang', '')
if lang == None:
lang = 'en'
return lang
# Tranlsate a string to any language
def translateval(value, lang, src=None):
src = src if src != None else 'en'
if lang == src:
return value
trans = Translation.objects.filter(value=value,lang=lang,src=src if src != None else 'en') # Get the translation
if trans.count() > 0: # Return it if it exists
return trans.first().translated
else: # Otherwise create it
originalvalue = value
value = value.replace('\n', '[=NEWLINE=]') # Preserve newlines
translation = ''
try:
translation = requests.request("GET", url, headers=headers, params={"text": value, "to": lang, "from": src if src != None else 'en', 'protected_words': '@;[=NEWLINE=];'}).json()['translated_text'][lang]'protected_words>
except:
translation = value
translation = translation.replace('[=NEWLINE=]', '\n').replace('[= NEWLINE =]','\n').replace('[=NEWLINE =]', '\n') # Newline fix, to preserve newlines
ntrans = Translation.objects.create(value=originalvalue,lang=lang,src=src if src != None else 'en', translated=translation) # Create a new translation
ntrans.save()
return ntrans.translated # Return the translated value
# A template filter to translate from english to any language
@register.filter('etran') # Register the filter to translate
def etran(value):
lang = get_lang() # Get the language
translation = None
if not lang == 'en':
try:
translation = translateval(value, lang, 'en') # Translate using NLP translation
except:
translation = None
if translation != None:
return translation
return value
{{ 'Here is some text. This text will be translated from English to another language'|etran }}
Comments (0) Comment
© Uglek, 2022